Find this useful? Enter your email to receive occasional updates for securing PHP code.
Signing you up...
Thank you for signing up!
PHP Decode
<?php $_stopwatch = microtime(); define("E2_VERSION", 4134); define("E2_RELEASE", "11.3..
Decoded Output download
<?php
$_stopwatch = microtime();
define("E2_VERSION", 4134);
define("E2_RELEASE", "11.3");
define("CACHE", 1);
define("BUILDER_OBFUSCATE", 1);
define("BUILDER_FLATTEN", 1);
define("BUILT", !strstr(__FILE__, "all.php"));
define("E2_RUN_ID", chr(rand(65, 90)));
function e2m_error404()
{
global $_config, $_strings;
if ($_config["try_redirect_to_all"]) {
$c = "all/" . urldecode((string) @$_GET["go"]);
rq($c);
}
header("HTTP/1.1 404 Not found");
$v["class"] = "404";
$v["heading"] = $_strings["pt--page-not-found"];
$v["title"] = $_strings["pt--page-not-found"];
return $v;
}
class AeArbitraryNotesCollectionView
{
private $name = "";
private $isCached = false;
private $hasRun = false;
private $sql = null;
private $currentURL = null;
private $cacheFilename = null;
private $cacheExpiresFilename = null;
private $cacheable = [];
private $viewExpiration = null;
private $notesCTree = null;
private $filterOutIDs = [];
public function __construct($name)
{
$this->name = $name;
}
public function setSQLRequest($sql)
{
$this->sql = $sql;
}
public function setCurrentURL($currentURL)
{
$this->currentURL = $currentURL;
}
public function setCacheFilename($cacheFilename)
{
$this->isCached = true;
$this->cacheFilename = $cacheFilename;
}
public function setCacheExpiresFilename($cacheExpiresFilename)
{
$this->cacheExpiresFilename = $cacheExpiresFilename;
}
public function setViewExpiration($viewExpiration)
{
$this->viewExpiration = $viewExpiration;
}
public function setFilterOutIDs($filterOutIDs)
{
$this->filterOutIDs = $filterOutIDs;
}
public function orderNotesCTreeByVerticality()
{
if (!$this->hasRun) {
$this->run();
}
usort($this->notesCTree, function ($b, $y) {
if (empty($b["images"][0]["verticality"])) {
$n = 0;
} else {
$n = $b["images"][0]["verticality"];
}
if (empty($y["images"][0]["verticality"])) {
$m = 0;
} else {
$m = $y["images"][0]["verticality"];
}
return (int) round(($m - $n) * 10000);
});
}
public function getNotesCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->notesCTree;
}
private function prepareCacheableData()
{
$f = [
"notes-records" => function () {
$d = [];
try {
sm($this->sql, 'get "' . $this->name . '" list');
foreach (qm() as $s) {
if (ff($s) === "public") {
$d[] = $s;
}
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Could not get list from database");
}
}
return $d;
},
];
if ($this->isCached and is_file($this->cacheFilename)) {
($this->cacheable = @unserialize(
file_get_contents($this->cacheFilename)
)) or ($this->cacheable = []);
}
$q = true;
if (!empty($this->cacheExpiresFilename)) {
if ($this->isCached and is_file($this->cacheExpiresFilename)) {
$l = time();
$z = (int) @file_get_contents($this->cacheExpiresFilename);
if (Log::$a) {
__log(
"List expires " .
date("r", $z) .
", now " .
date("r", $l)
);
}
$q = $l < $z;
}
}
$k = false;
foreach ($f as $x => $e_) {
if (!array_key_exists($x, $this->cacheable) or !$q) {
if (Log::$a) {
__log('Build cache: "' . $x . '"');
}
$this->cacheable[$x] = $e_();
$k = true;
} else {
if (Log::$a) {
__log('Retrieved from cache: "' . $x . '"');
}
}
}
if ($this->isCached and $k) {
e3($this->cacheFilename, serialize($this->cacheable));
if ($this->cacheExpiresFilename) {
@e3(
$this->cacheExpiresFilename,
time() + $this->viewExpiration
);
}
}
}
private function run()
{
$this->hasRun = true;
if (Log::$a) {
__log('AeArbitraryNotesCollectionView "' . $this->name . '" run {');
}
if (Log::$a) {
__log("Cacheable data {");
}
$this->prepareCacheableData();
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Uncacheable data {");
}
$this->notesCTree = [];
foreach ($this->cacheable["notes-records"] as $s) {
if (in_array($s["ID"], $this->filterOutIDs)) {
continue;
}
$noteView = new AeNoteView($s);
$r = $noteView->getNoteCTree();
$r["current?"] = $r["href"] == $this->currentURL;
$this->notesCTree[] = $r;
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$s["ID"]
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("}");
}
}
}
class AeDatabaseConfiguration
{
public $server;
public $host;
public $port = null;
public $user;
public $password;
public $name;
public $source;
public $backup_dir;
private $prefix = null;
private $subset = null;
public function __construct(
$source,
$backup_dir,
$server,
$user,
$password,
$name,
$prefix = null,
$subset = null
) {
$this->source = $source;
$this->backup_dir = $backup_dir;
$this->server = $server;
list($this->host, $this->port) = tm($this->server);
if ((string) $this->port === "") {
$this->port = null;
}
$this->user = $user;
$this->password = $password;
$this->name = $name;
$this->prefix = $prefix;
$this->subset = $subset;
}
public function hasPrefixSpecified()
{
return $this->prefix !== null;
}
public function getPrefix()
{
if ($this->prefix === null) {
throw new LogicException(
"Assertion failed: database configuration has no prefix"
);
}
return $this->prefix;
}
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
public function hasSubsetSpecified()
{
return $this->subset !== null;
}
public function setSubset($subset)
{
$this->subset = $subset;
}
public function getSubset()
{
if ($this->subset === null) {
throw new LogicException(
"Assertion failed: database configuration has no subset"
);
}
return $this->subset;
}
public function getDatabaseParamsArray()
{
return [
"server" => $this->server,
"user_name" => $this->user,
"passw" => $this->password,
"name" => $this->name,
];
}
public function getServerKeyString()
{
return $this->user . "@" . $this->server;
}
public function getDatabaseKeyString()
{
return $this->getServerKeyString() . "/" . $this->name;
}
public function getTablesKeyString()
{
return $this->getDatabaseKeyString() . "/" . $this->getPrefix() . "...";
}
public function __toString()
{
return $this->getTablesKeyString() . "?" . $this->getSubset();
}
}
class AeEnv
{
private static $t = false;
public static $j = "";
public static $h = "http";
public static $g = "";
public static $server = "";
public static $w = "";
public static $u = "";
public static $i = "http";
public static $o = "";
public static $p = "";
private static function updateBaseURL()
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
self::$o = self::$i . "://" . self::$server . self::$w . "/";
self::$p = self::$o;
if (self::$u !== (string) "") {
self::$p .= self::$u . "/";
}
}
public static function examine($cv)
{
list(self::$server) = explode(":", $cv["HTTP_HOST"]);
self::$w = substr(
$cv["PHP_SELF"],
0,
strpos($cv["PHP_SELF"], "/index.php")
);
self::$i =
(!empty($cv["HTTPS"]) && $cv["HTTPS"] !== "off" or
$cv["SERVER_PORT"] == 443 or
isset($cv["HTTP_X_FORWARDED_PROTO"]) &&
$cv["HTTP_X_FORWARDED_PROTO"] == "https" or
isset($cv["HTTP_X_HTTPS"]) && $cv["HTTP_X_HTTPS"])
? "https"
: "http";
if (getenv("E2_USER_SUBPATH")) {
self::$u = getenv("E2_USER_SUBPATH");
} elseif (getenv("REDIRECT_E2_USER_SUBPATH")) {
self::$u = getenv("REDIRECT_E2_USER_SUBPATH");
}
self::$t = true;
self::updateBaseURL();
self::$j = self::$server;
self::$h = self::$i;
self::$g = self::$o;
}
public static function setPrefersHTTPS($vv)
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
if ((bool) $vv) {
self::$i = "https";
self::updateBaseURL();
}
}
public static function setPreferredServer($bv)
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
if ($bv !== null and $_SERVER["HTTP_HOST"] !== $bv) {
self::$server = $bv;
self::updateBaseURL();
}
}
public static function showDie()
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
echo "<pre>";
echo '<b>server</b>: "' . self::$server . '"<br />';
echo '<b>server_used</b>: "' . self::$j . '"<br />';
echo '<b>folder</b>: "' . self::$w . '"<br />';
echo '<b>user_subpath</b>: "' . self::$u . '"<br />';
echo '<b>protocol_used</b>: "' . self::$h . '"<br />';
echo '<b>protocol</b>: "' . self::$i . '"<br />';
echo '<b>base_url_used</b>: "' . self::$g . '"<br />';
echo '<b>base_url</b>: "' . self::$o . '"<br />';
echo "</pre>";
die();
}
}
class AeFileManager
{
private static $yv = null;
private static $nv = null;
private static $mv = null;
private static $fv = ["."];
private static $dv = ["", LOGS_DIRNAME, BACKUP_DIRNAME];
private static $sv = ["", CACHES_DIRNAME, BACKUP_DIRNAME];
private static $av = [
PICTURES_DIRNAME,
THUMBNAILS_DIRNAME,
PICTURES_DIRNAME . "remote/",
THUMBNAILS_DIRNAME . "remote/",
VIDEO_DIRNAME,
AUDIO_DIRNAME,
AVATARS_DIRNAME,
USERPIC_DIRNAME,
];
private static $qv = ["updating.psa"];
private static $lv = [
"password-hash.psa",
"password-wait.psa",
"last-comment.psa",
"new-uploads.psa",
"settings.json",
"bsi.psa",
"auth.psa",
"scheduled.psa",
"license.psa",
"checklist.psa",
];
private static function ready()
{
return self::$yv !== null and self::$nv !== null and self::$mv !== null;
}
public static function writtenDirectories($nv = null, $mv = null)
{
if (!self::ready()) {
return [];
}
if ($nv === null) {
$nv = self::$nv;
}
if ($mv === null) {
$mv = self::$mv;
}
$zv = self::$fv;
foreach (self::$dv as $kv) {
$zv[] = self::$yv . $kv;
}
foreach (self::$sv as $kv) {
$zv[] = $nv . $kv;
}
foreach (self::$av as $kv) {
$zv[] = $mv . $kv;
}
$zv = array_unique($zv);
return $zv;
}
public static function writtenFiles($nv = null, $mv = null)
{
if (!self::ready()) {
return [];
}
if ($nv === null) {
$nv = self::$nv;
}
if ($mv === null) {
$mv = self::$mv;
}
$xv = [];
foreach (self::$qv as $ev) {
$xv[] = self::$yv . $ev;
}
foreach (self::$lv as $ev) {
$xv[] = $nv . $ev;
}
$xv = array_unique($xv);
return $xv;
}
public static function setInstancePath($yv)
{
self::$yv = $yv;
}
public static function setUserPath($nv)
{
self::$nv = $nv;
}
public static function setMediaPath($mv)
{
self::$mv = $mv;
}
public static function forceAllDirectories()
{
if (!self::ready()) {
return false;
}
foreach (self::writtenDirectories() as $rv) {
@nq($rv);
}
}
public static function forceInstanceDirectories()
{
if (!self::ready()) {
return false;
}
foreach (self::$dv as $kv) {
@nq(self::$yv . $kv);
}
}
public static function forceUserDirectories($nv = null)
{
if (!self::ready()) {
return false;
}
if ($nv === null) {
$nv = self::$nv;
}
foreach (self::$sv as $kv) {
@nq($nv . $kv);
}
}
public static function forceMediaDirectories($mv = null)
{
if (!self::ready()) {
return false;
}
if ($mv === null) {
$mv = self::$mv;
}
foreach (self::$av as $kv) {
@nq($mv . $kv);
}
}
public static function getPathsWithNoWritePermissions(
$nv = null,
$mv = null
) {
if (!self::ready()) {
return [];
}
if ($nv === null) {
$nv = self::$nv;
}
if ($mv === null) {
$mv = self::$mv;
}
clearstatcache();
$tv = [];
foreach (self::writtenDirectories($nv, $mv) as $jv) {
if (is_dir($jv) and !is_writable($jv)) {
$tv[] = $jv;
}
}
foreach (self::writtenFiles($nv, $mv) as $jv) {
if (is_file($jv) and !is_writable($jv)) {
$tv[] = $jv;
}
}
return $tv;
}
}
class AeLayoutDiversityManager
{
private static $layoutsUseIndexes = [];
private static $layoutsUseIndex = 1;
private static $layoutsUseMaxIndex = 1;
public static function addLayoutsUsed($hv)
{
self::$layoutsUseIndexes[$hv] = self::$layoutsUseIndex;
self::$layoutsUseIndex++;
self::$layoutsUseMaxIndex++;
}
public static function hasLayoutBeenUsed($hv)
{
if (isset(self::$layoutsUseIndexes[$hv])) {
return true;
}
}
public static function getLayoutsUseRecency($hv)
{
if (isset(self::$layoutsUseIndexes[$hv])) {
return self::$layoutsUseIndexes[$hv] - self::$layoutsUseMaxIndex;
}
}
}
class AeMainMenuManager
{
private static $currentTags = [];
private static $parentTags = [];
static $isFavouritesCurrent = false;
static $isFavouritesParent = false;
static $isMostCommentedCurrent = false;
static $isMostCommentedParent = false;
static $isPopularCurrent = false;
static $isPopularParent = false;
static $isTagsCurrent = false;
static $isTagsParent = false;
static $isCalendarCurrent = false;
static $isCalendarParent = false;
public static function addCurrentTag($gv)
{
self::$currentTags[] = $gv;
}
public static function addParentTag($gv)
{
self::$parentTags[] = $gv;
}
public static function isCurrentTag($gv)
{
if (!empty(self::$currentTags)) {
return in_array($gv, self::$currentTags);
}
return false;
}
public static function isParentTag($gv)
{
if (!empty(self::$parentTags)) {
return in_array($gv, self::$parentTags);
}
return false;
}
}
class AeModel
{
private static $wv = [
"key" => "INT UNSIGNED AUTO_INCREMENT PRIMARY KEY",
"pkey" => "INT UNSIGNED DEFAULT '0' NOT NULL",
"pkey1" => "INT UNSIGNED DEFAULT '1' NOT NULL",
"int" => "INT DEFAULT '0' NOT NULL",
"uint" => "INT UNSIGNED DEFAULT '0' NOT NULL",
"time" => "INT UNSIGNED DEFAULT '0' NOT NULL",
"0" => "TINYINT(1) DEFAULT '0' NOT NULL",
"1" => "TINYINT(1) DEFAULT '1' NOT NULL",
"v1" => "VARCHAR(1) DEFAULT '' NOT NULL",
"v8" => "VARCHAR(8) DEFAULT '' NOT NULL",
"v15" => "VARCHAR(15) DEFAULT '' NOT NULL",
"v32" => "VARCHAR(32) DEFAULT '' NOT NULL",
"v39" => "VARCHAR(39) DEFAULT '' NOT NULL",
"v64" => "VARCHAR(64) DEFAULT '' NOT NULL",
"fid" => "VARCHAR(32) DEFAULT '" . DEFAULT_FORMATTER . "' NOT NULL",
"v255" => "VARCHAR(255) DEFAULT '' NOT NULL",
"text" => "MEDIUMTEXT",
];
private static $uv = [
"Actions" => [
["ID", "key"],
["SubsetID", "pkey1"],
["EntityID", "pkey"],
["Stamp", "time"],
["ReadCount", "int"],
],
"Aliases" => [
["ID", "key"],
["SubsetID", "pkey1"],
["EntityType", "v1"],
["EntityID", "pkey"],
["Alias", "v64"],
["Stamp", "time"],
],
"Comments" => [
["ID", "key"],
["SubsetID", "pkey1"],
["NoteID", "pkey"],
["AuthorName", "v255"],
["AuthorEmail", "v255"],
["Text", "text"],
["Reply", "text"],
["IsVisible", "1"],
["IsFavourite", "0"],
["IsReplyVisible", "0"],
["IsReplyFavourite", "0"],
["IsAnswerAware", "1"],
["IsSubscriber", "0"],
["IsSpamSuspect", "0"],
["IsNew", "0"],
["Stamp", "time"],
["LastModified", "time"],
["ReplyStamp", "time"],
["ReplyLastModified", "time"],
["IP", "v39"],
["IsGIPUsed", "0"],
["GIP", "v15"],
["GIPAuthorID", "v64"],
],
"GIPsSessions" => [
["ID", "key"],
["SubsetID", "pkey1"],
["GIP", "v15"],
["GIPAuthorID", "v64"],
["AuthorName", "v255"],
["AuthorEmail", "v255"],
["AuthorProfileLink", "v255"],
["SessionToken", "v255"],
["Stamp", "time"],
],
"Keywords" => [
["ID", "key"],
["SubsetID", "pkey1"],
["Keyword", "v255"],
["OriginalAlias", "v64"],
["PageTitle", "v255"],
["Description", "text"],
["Summary", "text"],
["Uploads", "text"],
["IsVisible", "1"],
["IsFavourite", "0"],
],
"Notes" => [
["ID", "key"],
["SubsetID", "pkey1"],
["Title", "v255"],
["Text", "text"],
["Summary", "text"],
["FormatterID", "fid"],
["OriginalAlias", "v64"],
["Uploads", "text"],
["IsPublished", "0"],
["IsCommentable", "0"],
["IsVisible", "1"],
["IsFavourite", "0"],
["Stamp", "time"],
["LastModified", "time"],
["Offset", "int"],
["IsDST", "0"],
["IsIndexed", "0"],
["IsExternal", "0"],
["ReadCount", "uint"],
["SourceID", "pkey"],
["SourceNoteID", "pkey"],
["SourceNoteURL", "v255"],
["SourceNoteJSONURL", "v255"],
["SourceNoteData", "text"],
],
"NotesKeywords" => [
["ID", "key"],
["SubsetID", "pkey1"],
["NoteID", "pkey"],
["KeywordID", "pkey"],
],
"Sources" => [
["ID", "key"],
["SubsetID", "pkey1"],
["TrueID", "pkey"],
["Title", "v255"],
["AuthorName", "v255"],
["URL", "v255"],
["PictureURL", "v255"],
["IsWhiteListed", "0"],
["IsTrusted", "0"],
],
];
private static $iv = [
"Actions" => [
["unique", ["EntityID", "Stamp"]],
["index", ["SubsetID"]],
],
"Aliases" => [
["index", ["SubsetID"]],
["index", ["Alias"]],
["index", ["EntityID"]],
],
"Comments" => [["index", ["SubsetID"]], ["index", ["NoteID"]]],
"GIPsSessions" => [
["unique", ["SubsetID", "GIP", "GIPAuthorID"]],
["index", ["SubsetID"]],
],
"Keywords" => [["index", ["SubsetID"]]],
"Notes" => [
["fulltext", ["Title", "Text"]],
["index", ["SubsetID"]],
["index", ["Stamp"]],
["index", ["SourceID"]],
["index", ["SourceNoteID"]],
],
"NotesKeywords" => [["index", ["SubsetID"]], ["index", ["NoteID"]]],
"Sources" => [["index", ["SubsetID"]]],
];
private static $ov = [
"index" => "INDEX",
"unique" => "UNIQUE INDEX",
"fulltext" => "FULLTEXT",
];
private static $pv = [
"index" => "KEY",
"unique" => "UNIQUE KEY",
"fulltext" => "FULLTEXT KEY",
];
public static function unprefixedCoreTablesNames()
{
return array_keys(self::$uv);
}
public static function unprefixedEssentialTablesNames()
{
return ["Comments", "Keywords", "Notes", "NotesKeywords"];
}
public static function assertUnprefixedTableName($cb)
{
if (!array_key_exists($cb, self::$uv)) {
throw new LogicException(
'Table "' . $cb . '" is not part of the model'
);
}
}
public static function columnsByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
return self::$uv[$cb];
}
public static function indexesByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
return self::$iv[$cb];
}
public static function softFieldsByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
$vb = [];
foreach (self::$uv[$cb] as $x) {
if (!in_array($x[1], ["key"])) {
$vb[] = $x[0];
}
}
return $vb;
}
public static function columnsAndIndexesSQLByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
$bb = [];
foreach (self::columnsByUnprefixedTableName($cb) as $yb) {
list($name, $nb) = $yb;
$bb[] = "`" . $name . "` " . self::expandColumnDefinition($nb);
}
foreach (self::indexesByUnprefixedTableName($cb) as $mb) {
list($type, $fb) = $mb;
$db = implode("", $fb);
$sb =
self::indexCreateSQLByIndexType($type) .
" `" .
$db .
"` (`" .
implode("`, `", $fb) .
"`)";
$bb[] = $sb;
}
return "(" . implode(", ", $bb) . ")";
}
public static function expandColumnDefinition($ab)
{
return self::$wv[$ab];
}
public static function indexCheckSQLByIndexType($qb)
{
return self::$pv[$qb];
}
public static function indexCreateSQLByIndexType($qb)
{
return self::$ov[$qb];
}
}
class AeNoteReadCountsProvider
{
private static $dataByNoteID = [];
private static $hasRun = false;
private static $sql = null;
public static function setSQLRequestTemplateToMapIDsToReadCounts($sql)
{
self::$sql = $sql;
}
public static function requestDeferredReadCountForNoteID($noteID)
{
self::$dataByNoteID[$noteID] = false;
}
public static function getReadCountForNoteID($noteID)
{
if (self::$sql === null) {
return false;
}
if (!self::$hasRun) {
self::run();
}
if (empty(self::$dataByNoteID[$noteID])) {
return false;
}
return self::$dataByNoteID[$noteID];
}
private static function run()
{
self::$hasRun = true;
$lb = [];
foreach (self::$dataByNoteID as $note_id => $zb) {
$lb[] = "(`ID` = " . $note_id . ")";
}
if (!count($lb)) {
return;
}
$lb = implode(" OR ", $lb);
try {
sm(
self::$sql . " AND (" . $lb . ")",
"get all requested read counts for notes"
);
$kb = qm();
foreach ($kb as $xb) {
self::$dataByNoteID[$xb["ID"]] = $xb["ReadCount"];
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Could not get requested read counts for notes");
}
}
}
}
class AeNoteView
{
private $noteRecord = [];
private $isCached = false;
private $hasRun = false;
private $cacheFilename = null;
private $noteCTree = null;
private $highlightedTags = null;
private $cacheable = [];
private $OGImages = [];
private $wantRichText = false;
private $wantCommentsLink = false;
private $wantNewCommentsCount = false;
private $wantReadHref = false;
private $wantPreviewHref = false;
private $wantControls = false;
private $wantHiddenTags = false;
private $wantSharingButtons = false;
private $wantRelatedNotes = false;
private $filterOutRelatedNoteIDs = [];
private $useLocalHref = false;
public function __construct($noteRecord)
{
$this->noteRecord = $noteRecord;
if (CACHE_NOTES) {
$this->isCached = true;
$this->cacheFilename = e2_note_cache_filename_with_id_(
$noteRecord["ID"]
);
}
}
public function setHighlightedTags($highlightedTags)
{
$this->highlightedTags = $highlightedTags;
}
public function setWantRichText($wantRichText)
{
$this->wantRichText = $wantRichText;
}
public function setWantCommentsLink($wantCommentsLink)
{
$this->wantCommentsLink = $wantCommentsLink;
}
public function setWantNewCommentsCount($wantNewCommentsCount)
{
$this->wantNewCommentsCount = $wantNewCommentsCount;
}
public function setWantReadHref($wantReadHref)
{
$this->wantReadHref = $wantReadHref;
}
public function setWantPreviewHref($wantPreviewHref)
{
$this->wantPreviewHref = $wantPreviewHref;
}
public function setWantControls($wantControls)
{
$this->wantControls = $wantControls;
}
public function setWantHiddenTags($wantHiddenTags)
{
$this->wantHiddenTags = $wantHiddenTags;
}
public function setWantSharingButtons($wantSharingButtons)
{
$this->wantSharingButtons = $wantSharingButtons;
}
public function setWantRelatedNotes($wantRelatedNotes)
{
$this->wantRelatedNotes = $wantRelatedNotes;
}
public function setFilterOutRelatedNoteIDs($filterOutRelatedNoteIDs)
{
$this->filterOutRelatedNoteIDs = $filterOutRelatedNoteIDs;
}
public function setUseLocalHref($useLocalHref)
{
$this->useLocalHref = $useLocalHref;
}
public function getNoteCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->noteCTree;
}
private function prepareCacheableData()
{
$f = [
"title" => function () {
return ay(
htmlspecialchars(
$this->noteRecord["Title"],
ENT_NOQUOTES,
"UTF-8"
)
);
},
"text-format-info" => function () {
return ly(
$this->noteRecord["FormatterID"],
$this->noteRecord["Text"],
"full"
);
},
"summary" => function () {
if ((string) $this->noteRecord["Summary"] !== "") {
return ay(
htmlspecialchars(
$this->noteRecord["Summary"],
ENT_NOQUOTES,
"UTF-8"
)
);
} else {
$eb = $this->cacheable["text-format-info"]["text-flow"];
$rb = "";
foreach ($eb as $tb) {
if (is_string($tb)) {
$rb = $tb;
break;
}
}
$rb = ly($this->noteRecord["FormatterID"], $rb, "full");
return mf($rb["text-final"]);
}
},
"comments-count" => function () {
if (!$this->noteRecord["IsPublished"]) {
return false;
} else {
return ab($this->noteRecord["ID"]);
}
},
"tags-data" => function () {
$jb = ba($this->noteRecord["ID"]);
$hb["ctree"] = [];
$hb["all-resnames-uploads"] = [];
foreach ($jb as $gb => $wb) {
$hb["ctree"][] = [
"visible?" => (bool) $wb["IsVisible"],
"name" => htmlspecialchars(
$wb["Keyword"],
ENT_NOQUOTES,
"UTF-8"
),
"href" => eq("e2m_tag", ["*tag" => $wb]),
];
$hb["all-resnames-uploads"] = array_merge(
$hb["all-resnames-uploads"],
g3("tag", $wb["ID"])
);
}
$hb["all-resnames-uploads"] = array_unique(
$hb["all-resnames-uploads"]
);
return $hb;
},
];
if ($this->isCached and is_file($this->cacheFilename)) {
($this->cacheable = @unserialize(
file_get_contents($this->cacheFilename)
)) or ($this->cacheable = []);
}
$k = false;
foreach ($f as $x => $e_) {
if (!array_key_exists($x, $this->cacheable)) {
if (Log::$a) {
__log('Build cache: "' . $x . '"');
}
$this->cacheable[$x] = $e_();
$k = true;
} else {
if (Log::$a) {
__log('Retrieved from cache: "' . $x . '"');
}
}
}
if ($this->isCached and $k) {
e3($this->cacheFilename, serialize($this->cacheable));
}
}
private function run()
{
$this->hasRun = true;
if (Log::$a) {
__log("AeNoteView run {");
}
if (Log::$a) {
__log("Cacheable data {");
}
$this->prepareCacheableData();
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Uncacheable data {");
}
$ub = false;
if ($this->noteRecord["IsPublished"]) {
if ((string) $this->noteRecord["OriginalAlias"] !== "") {
$ub = eq("e2m_note", [
"alias" => $this->noteRecord["OriginalAlias"],
]);
} else {
$ib = $this->noteRecord;
$ib["__force_ymdn"] = true;
$ub = eq("e2m_note", ["*note" => $ib]);
}
}
$ob = ia($this->noteRecord);
$pb = [(int) $this->noteRecord["LastModified"], $ob];
$l = $this->noteRecord["IsPublished"]
? [(int) $this->noteRecord["Stamp"], $ob]
: $pb;
$c3 = ff($this->noteRecord);
$v3 = @$this->cacheable["text-format-info"]["meta"][
"resources-detected"
];
if (!is_array($v3)) {
$v3 = [];
}
if (count($v3)) {
w2($v3);
}
$b3 = z2($v3);
($y3 = @unserialize($this->noteRecord["Uploads"])) or ($y3 = []);
$n3 = array_merge(
k2($v3, $y3),
$this->cacheable["tags-data"]["all-resnames-uploads"]
);
$m3 = t3($n3);
$f3 = z2($n3);
$d3 = $this->noteRecord["SourceNoteData"];
$d3 = @json_decode($d3, true);
($s3 = @$d3["og_images"][0]) or ($s3 = "");
if ($this->noteRecord["IsExternal"]) {
$a3 = bn($this->noteRecord);
} else {
$a3 = [];
}
$q3 = false;
$z3 = $this->cacheable["tags-data"]["ctree"];
foreach ($z3 as $k3 => $x3) {
if ($this->highlightedTags !== null) {
$z3[$k3]["current?"] = in_array(
$z3[$k3]["name"],
$this->highlightedTags
);
}
if (!$this->wantHiddenTags and !$z3[$k3]["visible?"]) {
unset($z3[$k3]);
}
}
if ($this->wantSharingButtons and $c3 === "public") {
$e3 = os($m3);
} else {
$e3 = false;
}
if ($this->wantNewCommentsCount) {
$r3 = sb($this->noteRecord["ID"]);
} else {
$r3 = false;
}
$this->noteCTree = [
"id" => (int) $this->noteRecord["ID"],
"title" => (string) $this->cacheable["title"],
"href" => eq("e2m_note", ["*note" => $this->noteRecord]),
"href-original" => $ub,
"time" => $l,
"last-modified" => $pb,
"text" =>
(string) $this->cacheable["text-format-info"]["text-final"],
"format-info" => $this->cacheable["text-format-info"]["meta"],
"summary" => (string) $this->cacheable["summary"],
"snippet-text" => (string) $this->cacheable["summary"],
"draft?" => $c3 === "draft",
"scheduled?" => $c3 === "scheduled",
"public?" => $c3 === "public",
"hidden?" => $c3 === "hidden",
"current?" => false,
"favourite?" =>
(bool) ($this->noteRecord["IsFavourite"] and $c3 !== "draft"),
"images" => x2($b3),
"thumbs" => e2_($b3),
"source-main-image-url" => (string) $s3,
"og-images" => $m3,
"og-images-thumbs" => e2_($f3),
"tags" => $z3,
"sharing-buttons" => $e3,
"related" => $q3,
"read-href" =>
($this->wantReadHref and $this->noteRecord["IsPublished"])
? eq("e2m_note_read", ["*note" => $this->noteRecord])
: false,
"preview-href" =>
($this->wantPreviewHref and $c3 !== "public")
? eq("e2m_note", [
"*note" => $this->noteRecord,
"preview-key" => af($this->noteRecord),
])
: false,
"comments-count" => $this->cacheable["comments-count"],
"comments-count-text" => is_int($this->cacheable["comments-count"])
? e2l_get_string("gs--n-comments", [
"number" => $this->cacheable["comments-count"],
])
: "",
"new-comments-count" => $r3,
"new-comments-count-text" => is_int($r3)
? e2l_get_string("gs--comments-n-new", ["number" => $r3])
: "",
"comments-link?" =>
(bool) ($this->wantCommentsLink and
$this->noteRecord["IsPublished"] and
(xb($this->noteRecord) or
$this->cacheable["comments-count"] > 0)),
];
if ($this->noteRecord["IsExternal"]) {
$this->noteCTree = array_merge($this->noteCTree, $a3);
$this->noteCTree["href-original"] =
$this->noteCTree["href-external"];
if (!$this->useLocalHref) {
$this->noteCTree["href"] = $this->noteCTree["href-external"];
}
}
if ($this->wantControls) {
$this->noteCTree["edit-href"] = eq("e2m_note_edit", [
"*note" => $this->noteRecord,
]);
if (
$this->noteRecord["IsPublished"] and
!$this->noteRecord["IsVisible"]
) {
$this->noteCTree["show-action"] = eq("e2s_note_flag", [
"*note" => $this->noteRecord,
"flag" => "IsVisible",
"value" => 1,
]);
}
if ($this->noteRecord["IsPublished"]) {
$this->noteCTree["favourite-toggle-action"] = eq(
"e2s_note_flag_favourite",
[
"*note" => $this->noteRecord,
"value" => !$this->noteRecord["IsFavourite"],
]
);
}
}
$this->noteCTree["href-comments"] =
$this->noteCTree["href"] . "#comments";
if (Log::$a) {
__log("}");
}
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$this->noteRecord["ID"]
);
if (Log::$a) {
__log("}");
}
}
}
class AePageableNotesView
{
private $candy;
private $parameters;
private $pageExists = false;
private $isCached = false;
private $hasRun = false;
private $sql = null;
private $sql_count = null;
private $highlightedTags = null;
private $cacheFilename = null;
private $prevPageTitle = null;
private $nextPageTitle = null;
private $totalNotes = null;
private $totalPages = null;
private $notesCTree = null;
private $pagesCTree = null;
private $wantPaging = false;
private $wantNewCommentsCount = false;
private $wantReadHrefs = false;
private $wantPreviewHrefs = false;
private $wantControls = false;
private $wantHiddenTags = false;
private $wantRelatedNotes = false;
private $useLocalHrefs = false;
private $page = 1;
private $limit = 10;
public function __construct($candy, $parameters)
{
$this->candy = $candy;
$this->parameters = $parameters;
if (empty($parameters["page"])) {
$this->page = 1;
} else {
$this->page = (int) $parameters["page"];
}
}
public function setSQLCountRequest($sql_count)
{
if (strpos($sql_count, "SELECT COUNT(*) Total FROM ") !== 0) {
die(
'AePageableNotesView: Count request must start with "SELECT COUNT(*) Total FROM "'
);
}
$this->sql_count = $sql_count;
}
public function setLimitlessSQLRequest($sql)
{
if (strstr($sql, "LIMIT")) {
die('AePageableNotesView: Request must not contain "LIMIT"');
}
$this->sql = $sql;
if ($this->sql_count === null) {
if (strpos($sql, "SELECT * ") === 0) {
$this->sql_count = "SELECT COUNT(*) Total " . substr($sql, 9);
} else {
die("AePageableNotesView: setSQLCountRequest () must be used");
}
}
}
public function setPortionSize($limit)
{
$this->limit = abs((int) $limit);
}
public function setNextPrevPageTitles($nextPageTitle, $prevPageTitle)
{
$this->nextPageTitle = $nextPageTitle;
$this->prevPageTitle = $prevPageTitle;
}
public function setHighlightedTags($highlightedTags)
{
$this->highlightedTags = $highlightedTags;
}
public function setCacheFilename($cacheFilename)
{
$this->isCached = true;
$this->cacheFilename = $cacheFilename;
}
public function setWantPaging($wantPaging)
{
$this->wantPaging = $wantPaging;
}
public function setWantNewCommentsCount($wantNewCommentsCount)
{
$this->wantNewCommentsCount = $wantNewCommentsCount;
}
public function setWantReadHrefs($wantReadHrefs)
{
$this->wantReadHrefs = $wantReadHrefs;
}
public function setWantPreviewHrefs($wantPreviewHrefs)
{
$this->wantPreviewHrefs = $wantPreviewHrefs;
}
public function setWantControls($wantControls)
{
$this->wantControls = $wantControls;
}
public function setWantHiddenTags($wantHiddenTags)
{
$this->wantHiddenTags = $wantHiddenTags;
}
public function setWantRelatedNotes($wantRelatedNotes)
{
$this->wantRelatedNotes = $wantRelatedNotes;
}
public function setUseLocalHrefs($useLocalHrefs)
{
$this->useLocalHrefs = $useLocalHrefs;
}
public function isExistingPage()
{
if (!$this->hasRun) {
$this->run();
}
return $this->pageExists;
}
public function isFirstPage()
{
return $this->page === 1;
}
public function isFirstPageOfEmptyView()
{
if (!$this->hasRun) {
$this->run();
}
return $this->page === 1 and $this->totalPages === 0;
}
public function getTotalNotes()
{
if (!$this->hasRun) {
$this->run();
}
return $this->totalNotes;
}
public function getTotalPages()
{
if (!$this->hasRun) {
$this->run();
}
return $this->totalPages;
}
public function getNotesCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->notesCTree;
}
public function getPagesCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->pagesCTree;
}
private function prepareCacheableData()
{
$this->totalNotes = 0;
if ($this->limit) {
$t3 = ($this->page - 1) * $this->limit;
$this->sql .= " LIMIT " . $t3 . ", " . $this->limit;
}
sm(
$this->sql_count,
'count total notes of "' . $this->candy . '" list'
);
$j3 = qm();
$this->totalNotes = $j3 ? (int) $j3[0]["Total"] : 0;
sm($this->sql, 'get limited full notes "' . $this->candy . '" list');
$h3 = qm();
$l3 = [];
foreach ($h3 as $k3 => $s) {
$l3[] = $s["ID"];
}
$this->notesCTree = [];
foreach ($h3 as $k3 => $s) {
$noteView = new AeNoteView($s);
$noteView->setWantNewCommentsCount($this->wantNewCommentsCount);
$noteView->setWantReadHref($this->wantReadHrefs);
$noteView->setWantPreviewHref($this->wantPreviewHrefs);
$noteView->setWantControls($this->wantControls);
$noteView->setWantHiddenTags($this->wantHiddenTags);
$noteView->setWantCommentsLink(true);
$noteView->setWantRelatedNotes($this->wantRelatedNotes);
$noteView->setFilterOutRelatedNoteIDs($l3);
$noteView->setHighlightedTags($this->highlightedTags);
$noteView->setUseLocalHref($this->useLocalHrefs);
$this->notesCTree[] = $noteView->getNoteCTree();
}
$this->pagesCTree = [];
if (
$this->limit and
($this->totalPages = (int) ceil($this->totalNotes / $this->limit))
) {
$this->pagesCTree["timeline?"] = true;
$this->pagesCTree["count"] = (int) $this->totalPages;
$this->pagesCTree["this"] = (int) $this->page;
if ($this->wantPaging) {
$this->pagesCTree["earlier-title"] = $this->nextPageTitle;
$this->pagesCTree["later-title"] = $this->prevPageTitle;
$g3 = $this->parameters;
if ($this->page < $this->totalPages) {
$g3["page"] = $this->page + 1;
$this->pagesCTree["earlier-href"] = eq($this->candy, $g3);
}
if ($this->page > 1) {
$g3["page"] = $this->page - 1;
$this->pagesCTree["later-href"] = eq($this->candy, $g3);
}
}
}
}
private function run()
{
$this->hasRun = true;
if ($this->isCached and is_file($this->cacheFilename)) {
$w3 = @unserialize(file_get_contents($this->cacheFilename));
$this->totalNotes = @$w3["notes_total"];
$this->notesCTree = @$w3["notes_ctree"];
$this->pagesCTree = @$w3["pages_ctree"];
$this->totalPages = @$this->pagesCTree["count"];
}
if (
is_int($this->totalNotes) and
is_array($this->notesCTree) and
is_array($this->pagesCTree) and
is_int($this->totalPages)
) {
if (Log::$a) {
__log("Retrieved cached CTree");
}
} else {
$this->prepareCacheableData();
if ($this->isCached) {
e3(
$this->cacheFilename,
serialize([
"notes_total" => $this->totalNotes,
"notes_ctree" => $this->notesCTree,
"pages_ctree" => $this->pagesCTree,
])
);
}
}
foreach ($this->notesCTree as $u3) {
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$u3["id"]
);
if (empty($u3["related"]["each"])) {
continue;
}
foreach ($u3["related"]["each"] as $i3) {
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$i3["id"]
);
}
}
$this->pageExists =
($this->totalPages > 0 and
$this->page >= 1 and
$this->page <= $this->totalPages);
}
}
class AeRequest
{
public $method = "GET";
public $url = "";
public $candy = "";
public $parameters = [];
public function __construct($cv, $o3)
{
$this->method = $cv["REQUEST_METHOD"];
$p3 = urldecode((string) @$o3["go"]);
if (substr($p3, 0, strlen(AeEnv::$u)) === AeEnv::$u) {
$p3 = substr($p3, strlen(AeEnv::$u));
}
$this->url =
AeEnv::$h . "://" . AeEnv::$j . AeEnv::$w . AeEnv::$u . "/" . $p3;
list($this->candy, $this->parameters) = rq($p3);
}
public function toBeFulfilledByService()
{
return substr($this->candy, 0, 4) == "e2s_";
}
public function requiresInstallation()
{
return !in_array($this->candy, [
"e2s_build",
"e2m_info",
"e2m_install",
"e2j_check_db_config",
"e2j_list_databases",
"e2s_instantiate",
"e2s_install",
]);
}
public function requiresVersionMatch()
{
return $this->requiresInstallation();
}
public function requiresScheduleCheckBeforeServing()
{
return $this->requiresInstallation();
}
public function shouldSlowDownAJAXResponse()
{
return in_array($this->candy, [
"e2j_check_db_config",
"e2j_list_databases",
"e2j_check_password",
"e2j_userpic_upload",
"e2j_userpic_remove",
"e2j_file_upload",
"e2j_file_rename",
"e2j_file_remove",
"e2j_note_livesave",
"e2s_note_flag_favourite",
"e2s_comment_flag_ajax",
"e2s_tag_flag_ajax",
]);
}
public function requiresSignIn()
{
return !empty($this->candy) and
is_callable($this->candy) and
$this->requiresInstallation() and
!in_array($this->candy, [
"e2m_info",
"e2m_frontpage",
"e2m_rss",
"e2m_json",
"e2m_note",
"e2m_note_json",
"e2m_note_read",
"e2m_tags",
"e2m_tag",
"e2m_untagged",
"e2m_tag_rss",
"e2m_tag_json",
"e2m_popular",
"e2m_favourites",
"e2m_most_commented",
"e2m_found",
"e2m_comments",
"e2m_everything",
"e2m_sitemap_xml",
"e2m_year",
"e2m_month",
"e2m_day",
"e2m_calendar",
"e2m_unsubscribe",
"e2m_theme_preview",
"e2m_error404",
"e2m_password_reset",
"e2s_password_reset_email",
"e2m_password",
"e2s_password_save",
"e2s_sign_in",
"e2m_sign_out",
"e2m_gip_sign_in",
"e2m_gip_sign_in_callback",
"e2m_gip_sign_out",
"e2s_comment_process",
"e2s_search",
"e2s_bsi_step",
"e2j_check_password",
"e2s_retrieve",
"e2s_notify",
"e2s_dump",
]);
}
public function allowedInReadOnlyMode()
{
return !in_array($this->candy, [
"e2m_write",
"e2m_note_edit",
"e2s_note_process",
"e2s_note_publish",
"e2s_note_delete",
"e2s_note_flag_favourite",
"e2s_note_flag",
"e2m_comment_edit",
"e2m_comment_delete",
"e2m_comment_reply",
"e2m_comment_reply_delete",
"e2m_comment_flag",
"e2s_comment_flag_ajax",
"e2m_unsubscribe",
"e2s_comment_process",
"e2m_settings",
"e2m_timezone",
]);
}
public function replaceWith($cy)
{
$this->candy = $cy;
}
}
function c()
{
global $_config;
$vy = [
"new-note-href" => eq("e2m_write"),
"drafts-href" => eq("e2m_drafts", ["page" => 1]),
"drafts-count" => (int) nf(false, true),
"settings-href" => eq("e2m_settings"),
"theme-preview-href" => eq("e2m_theme_preview", ["theme" => ""]),
"password-href" => eq("e2m_password", ["recovery-key" => ""]),
"database-href" => eq("e2m_database"),
"timezone-href" => eq("e2m_timezone"),
"sessions-href" => eq("e2m_sessions"),
"sign-out-href" => eq("e2m_sign_out"),
];
if (us()) {
$vy["get-backup-href"] = eq("e2m_get_backup");
}
if (@$_config["read_only"]) {
unset($vy["new-note-href"]);
unset($vy["settings-href"]);
unset($vy["timezone-href"]);
}
if (!$_config["allow_themes_preview"]) {
unset($vy["theme-preview-href"]);
}
$databaseConfiguration = bl();
if (
$databaseConfiguration->source !== "settings" or
!$_config["allow_db_config"]
) {
unset($vy["database-href"]);
}
list($r3, $by) = lb($databaseConfiguration);
if ($r3) {
$vy["new-comments-count"] = $r3;
$vy["new-comments-href"] = $by;
}
return $vy;
}
function v($yy, AeDatabaseConfiguration $databaseConfiguration, $ny)
{
static $my = null;
$fy = ($yy === USER_DIR and $databaseConfiguration == bl());
if ($ny) {
if ($yy !== false) {
@unlink($yy . CACHE_FILENAME_ALIASMAP);
}
if ($fy) {
$my = null;
}
return;
}
if ($fy and is_array($my)) {
return $my;
}
$dy = null;
if (CACHE_ALIASMAP and is_file($yy . CACHE_FILENAME_ALIASMAP)) {
$dy = @unserialize(file_get_contents($yy . CACHE_FILENAME_ALIASMAP));
}
if (is_array($dy)) {
if ($fy) {
$my = $dy;
}
return $dy;
}
if (Log::$a) {
__log("Build aliasmap {");
}
$dy = [];
am(
$databaseConfiguration,
"SELECT `EntityType`, `EntityID`, `Alias` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Aliases` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `Stamp` IN (" .
"SELECT MAX(`Stamp`) `MaxStamp` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Aliases` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"GROUP BY `EntityType`, `EntityID`" .
")",
"get all active aliases"
);
foreach (qm() as $sy) {
$ay = $sy["EntityType"] . $sy["EntityID"];
$dy[$ay] = $sy["Alias"];
}
am(
$databaseConfiguration,
"SELECT `ID`, `Stamp`, `Offset`, `IsDST`, `OriginalAlias` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `IsPublished` = 1 " .
"ORDER BY `Stamp`",
"get all notes to cache y/d/m/n urls"
);
$qy = 0;
$ly = false;
foreach (qm() as $zy) {
$ay = "n" . $zy["ID"];
$ky = y1("Y/m/d", $zy["Stamp"], ia($zy));
if ($ky !== $ly) {
$qy = 0;
}
$qy++;
$xy = $ky . "/" . $qy;
if (empty($dy[$ay])) {
$dy[$ay] = $xy;
} else {
if ((string) $zy["OriginalAlias"] === "") {
$dy[$ay . "-ymdn"] = $xy;
}
}
$ly = $ky;
}
am(
$databaseConfiguration,
"SELECT `ID`, `OriginalAlias` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Keywords` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset(),
"get original active aliases for tags"
);
foreach (qm() as $wb) {
$ay = "t" . $wb["ID"];
if (empty($dy[$ay])) {
$dy[$ay] = $wb["OriginalAlias"];
}
}
if (CACHE_ALIASMAP) {
e3($yy . CACHE_FILENAME_ALIASMAP, serialize($dy));
}
if ($fy) {
$my = $dy;
}
if (Log::$a) {
__log("}");
}
return $dy;
}
function b($ny = false)
{
return v(USER_DIR, bl(), $ny);
}
function e2_alias_of_note_with_id_($ey)
{
$ry = b()["n" . $ey];
if (
preg_match(
'/^(?P<year>\d{4})\/(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<day_number>\d+)$/s',
$ry
)
) {
$ry = "";
}
return $ry;
}
function e2ali__alias_from_title_($source)
{
global $_config;
$ty = $source;
if (array_key_exists("autoreplace_for_aliases", $_config)) {
$ty = strtr($ty, $_config["autoreplace_for_aliases"]);
}
$ty = t1($ty);
$ty = str_replace('\'', "", $ty);
$ty = str_replace("", "", $ty);
$ty = str_replace(chr(146), "", $ty);
$jy = "";
for ($gb = 0; $gb < strlen($ty); ++$gb) {
if (
ord($ty[$gb]) >= 48 and ord($ty[$gb]) <= 57 or
ord($ty[$gb]) >= 65 and ord($ty[$gb]) <= 90 or
ord($ty[$gb]) >= 97 and ord($ty[$gb]) <= 122 or
0
) {
$jy .= $ty[$gb];
} else {
$jy .= "-";
}
}
$jy = preg_replace("/\-+/", "-", $jy);
$jy = trim($jy, "-");
$jy = strtolower($jy);
if ($jy == "-") {
$jy = "";
}
$jy = substr($jy, 0, ALIAS_MAX_LENGTH);
return $jy;
}
function m(AeDatabaseConfiguration $databaseConfiguration, $ry)
{
if ((string) $ry === "") {
return false;
}
am(
$databaseConfiguration,
"SELECT * FROM `" .
$databaseConfiguration->getPrefix() .
"Aliases` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `Alias` = '" .
$ry .
"' " .
"ORDER BY `Stamp` LIMIT 1",
'get alias record for alias "' . $ry . '"'
);
$h3 = qm();
if (count($h3) == 1) {
return $h3[0];
} else {
return false;
}
}
function f($ry)
{
if ((string) $ry === "") {
return false;
}
if (Log::$a) {
__log('Get entity type and id from alias "' . $ry . '"');
}
$hy = @array_flip(b());
$ay = (string) @$hy[$ry];
if (strlen($ay) > 0 and ($ay[0] == "n" or $ay[0] == "t")) {
$xb = ["type" => $ay[0], "id" => (int) substr($ay, 1)];
return $xb;
}
$sy = m(bl(), $ry);
if (!$sy) {
return false;
}
$xb = ["type" => $sy["EntityType"], "id" => (int) $sy["EntityID"]];
if (Log::$a) {
__log(
'Got entity type "' . $xb["type"] . '" and id "' . $xb["id"] . '"'
);
}
return $xb;
}
function d(
$yy,
AeDatabaseConfiguration $databaseConfiguration,
$iy,
$uy,
$gy,
$source,
$wy = 1
) {
if (Log::$a) {
__log(
'Aliases: "' .
$iy .
'" available alias for source "' .
$source .
'"'
);
}
$oy = $uy . $gy;
if ($iy === "set" and $oy === "") {
return false;
}
$jy = e2ali__alias_from_title_($source);
if ($source !== "" and $jy === "") {
$jy = (string) $wy;
} elseif ($wy > 1) {
$py = "-" . $wy;
$jy = substr($jy, 0, ALIAS_MAX_LENGTH - strlen($py)) . $py;
}
$dy = v($yy, $databaseConfiguration, false);
if ($sy = m($databaseConfiguration, $jy)) {
$cn = $sy["EntityType"] . $sy["EntityID"];
if ($oy === $cn or $jy !== $dy[$cn]) {
if ($iy == "find") {
return $jy;
}
if ($iy == "set") {
if (Log::$a) {
__log("Aliases: update alias timestamp");
}
fm($databaseConfiguration, "Aliases", [
"ID" => $sy["ID"],
"EntityType" => $uy,
"EntityID" => $gy,
"Alias" => $jy,
"Stamp" => time(),
]);
v($yy, $databaseConfiguration, true);
return $jy;
}
} else {
return d(
$yy,
$databaseConfiguration,
$iy,
$uy,
$gy,
$source,
$wy + 1
);
}
} else {
if ($oy !== "" and $jy == "") {
if (
preg_match(
"/(?P<year>\d{4})\/(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<day_number>\d+)/",
$dy[$oy]
)
) {
if (Log::$a) {
__log("Aliases: d/m/y/n was already used for this entity");
}
return "";
}
}
if (Log::$a) {
__log(
"Aliases: its an empty alias, and it was not being used for this entity"
);
}
if ($uy == "t" and ($vn = qa($databaseConfiguration, $jy))) {
if ($vn["ID"] != $gy) {
return d(
$yy,
$databaseConfiguration,
$iy,
$uy,
$gy,
$source,
$wy + 1
);
}
}
if ($iy == "find") {
return $jy;
}
if ($iy == "set") {
mm($databaseConfiguration, "Aliases", [
"EntityType" => $uy,
"EntityID" => $gy,
"Alias" => $jy,
"Stamp" => time(),
]);
v($yy, $databaseConfiguration, true);
return $jy;
}
}
return "";
}
function e2_delete_aliases_for_entity_($type, $ey)
{
global $_config;
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Aliases` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `EntityType` = '" .
$type .
"' " .
"AND `EntityID`=" .
((int) $ey),
"delete aliases of note"
);
}
function a()
{
static $bn;
$yn = ls();
if (empty($bn)) {
$bn = md5(AeEnv::$p . "email" . $yn);
}
return $bn;
}
function q()
{
static $nn;
$yn = ls();
if (empty($nn)) {
$nn = md5(AeEnv::$p . "nospam" . $yn . date("n-Y"));
}
return $nn;
}
function l()
{
static $mn;
$yn = ls();
if (empty($mn)) {
$mn = md5(
AeEnv::$p . "nospam" . $yn . date("n-Y", strtotime("-1 month"))
);
}
return $mn;
}
function z($note_id)
{
$yn = ls();
return x1("comment_" . md5(AeEnv::$p . "nospam_cookie" . $yn . $note_id));
}
function k()
{
$fn_ = $_SERVER["HTTP_USER_AGENT"];
$yn = ls();
return md5(AeEnv::$p . "nospam_cookie" . $yn . $fn_);
}
function x()
{
if (array_key_exists("email", $_POST) and $_POST["email"] !== "") {
return true;
}
$nn = q();
$mn = l();
if (!array_key_exists($nn, $_POST) and !array_key_exists($mn, $_POST)) {
return true;
}
if (
array_key_exists($nn, $_POST) and $_POST[$nn] !== "" or
array_key_exists($mn, $_POST) and $_POST[$mn] !== ""
) {
return true;
}
if (!array_key_exists("comment", $_POST) or strlen($_POST["comment"]) > 6) {
return true;
}
return false;
}
function e2_cookie_data_is_spam_suspicios_for_note_id_($note_id)
{
if (
!array_key_exists(z($note_id), $_COOKIE) or
$_COOKIE[z($note_id)] !== k()
) {
return true;
}
return false;
}
function e2m_year($parameters = [])
{
global $_strings, $_config;
$dn = $parameters["year"];
$sn = e2l_get_string("pt--nth-year", ["year" => $dn]);
if (!j($dn)) {
return e2m_error404();
}
AeMainMenuManager::$isCalendarCurrent = false;
AeMainMenuManager::$isCalendarParent = true;
$an = gmmktime(0, 0, 0, 1, 1, $dn - 1);
$qn = gmmktime(0, 0, 0, 1, 1, $dn + 1);
list($ln, $zn) = e2__fruitful_neighbours_with_ymd_($dn);
$kn = "e2m_year";
if ($ln) {
$xn["prev-href"] = eq($kn, e2__parameters_with_timestamp_($ln));
$xn["prev-jump?"] = (bool) (gmdate("Y", $an) != gmdate("Y", $ln));
$xn["prev-title"] = gmdate("Y", $ln);
}
if ($zn) {
$xn["next-href"] = eq($kn, e2__parameters_with_timestamp_($zn));
$xn["next-jump?"] = (bool) (gmdate("Y", $qn) != gmdate("Y", $zn));
$xn["next-title"] = gmdate("Y", $zn);
}
$xn["timeline?"] = false;
$xn["this"] = $dn;
$xn["this-title"] = $dn;
list($en, $rn) = s1($dn);
$vb = [
"title" => $sn,
"heading" => $sn,
"pages" => $xn,
"year" => (int) $dn,
"calendar" => t($dn, false, false),
];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df(ys()) .
"AND `Stamp` BETWEEN " .
$en .
" " .
"AND " .
$rn .
" " .
"ORDER BY `Stamp`",
"get all notes for the year"
);
$h3 = qm();
$tn = w(true, $h3, $dn);
if (count($tn)) {
$vb["notes-list"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
return $vb;
}
function e2m_month($parameters = [])
{
global $_strings, $_config;
$dn = $parameters["year"];
$jn = $parameters["month"];
$sn = e2l_get_string("pt--nth-month-of-nth-year", [
"year" => $dn,
"month" => $jn,
]);
if (!j($dn, $jn)) {
return e2m_error404();
}
AeMainMenuManager::$isCalendarCurrent = false;
AeMainMenuManager::$isCalendarParent = true;
$an = gmmktime(0, 0, 0, $jn - 1, 1, (int) $dn);
$qn = gmmktime(0, 0, 0, $jn + 1, 1, (int) $dn);
list($ln, $zn) = e2__fruitful_neighbours_with_ymd_($dn, $jn);
$kn = "e2m_month";
if ($ln) {
$xn["prev-href"] = eq($kn, e2__parameters_with_timestamp_($ln));
$xn["prev-jump?"] = (bool) (gmdate("Y/m", $an) != gmdate("Y/m", $ln));
$xn["prev-title"] = e2l_get_string("gs--nth-month-of-nth-year", [
"year" => gmdate("Y", $ln),
"month" => gmdate("n", $ln),
]);
}
if ($zn) {
$xn["next-href"] = eq($kn, e2__parameters_with_timestamp_($zn));
$xn["next-jump?"] = (bool) (gmdate("Y/m", $qn) != gmdate("Y/m", $zn));
$xn["next-title"] = e2l_get_string("gs--nth-month-of-nth-year", [
"year" => gmdate("Y", $zn),
"month" => gmdate("n", $zn),
]);
}
$xn["timeline?"] = false;
$xn["this-title"] = $sn;
list($en, $rn) = s1($dn, $jn);
$vb = [
"title" => $sn,
"heading" => $sn,
"calendar" => t($dn, $jn, false),
"pages" => $xn,
"year" => (int) $dn,
"month" => (int) $jn,
];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df(ys()) .
"AND `Stamp` BETWEEN " .
$en .
" " .
"AND " .
$rn .
" " .
"ORDER BY `Stamp`",
"get all notes for the month"
);
$h3 = qm();
$tn = w(true, $h3, $dn, $jn);
if (count($tn)) {
$vb["notes-list"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
return $vb;
}
function e2m_day($parameters = [])
{
global $_strings, $_config, $_current_url;
$dn = (int) $parameters["year"];
$jn = (int) $parameters["month"];
$hn = (int) $parameters["day"];
if (!j($dn, $jn, $hn)) {
return e2m_error404();
}
AeMainMenuManager::$isCalendarCurrent = false;
AeMainMenuManager::$isCalendarParent = true;
if ($_current_url === p()) {
AeMainMenuManager::$isCalendarCurrent = true;
AeMainMenuManager::$isCalendarParent = false;
}
$sn = e2l_get_string("pt--nth-day-of-nth-month-of-nth-year", [
"year" => $dn,
"month" => $jn,
"day" => $hn,
]);
$an = gmmktime(0, 0, 0, (int) $jn, $hn - 1, (int) $dn);
$qn = gmmktime(0, 0, 0, (int) $jn, $hn + 1, (int) $dn);
list($ln, $zn) = e2__fruitful_neighbours_with_ymd_($dn, $jn, $hn);
$kn = "e2m_day";
if ($ln) {
$xn["prev-href"] = eq($kn, e2__parameters_with_timestamp_($ln));
$xn["prev-jump?"] =
(bool) (gmdate("Y/m/d", $an) != gmdate("Y/m/d", $ln));
$xn["prev-title"] = e2l_get_string(
"gs--nth-day-of-nth-month-of-nth-year",
[
"year" => gmdate("Y", $ln),
"month" => gmdate("n", $ln),
"day" => gmdate("j", $ln),
]
);
}
if ($zn) {
$xn["next-href"] = eq($kn, e2__parameters_with_timestamp_($zn));
$xn["next-jump?"] =
(bool) (gmdate("Y/m/d", $qn) != gmdate("Y/m/d", $zn));
$xn["next-title"] = e2l_get_string(
"gs--nth-day-of-nth-month-of-nth-year",
[
"year" => gmdate("Y", $zn),
"month" => gmdate("n", $zn),
"day" => gmdate("j", $zn),
]
);
}
$xn["timeline?"] = false;
$xn["this-title"] = $sn;
$vb = [
"title" => $sn,
"heading" => $sn,
"pages" => $xn,
"calendar" => t($dn, $jn, $hn),
];
$h3 = om($dn, $jn, $hn);
$h3 = array_reverse($h3);
$gn = ys();
$tn = [];
foreach ($h3 as $k3 => $zy) {
if (!(ff($zy) === "public" or $gn and $zy["IsPublished"])) {
continue;
}
$noteView = new AeNoteView($zy);
$noteView->setWantNewCommentsCount($gn);
$noteView->setWantReadHref($_config["count_reads"]);
$noteView->setWantControls($gn and !@$_config["read_only"]);
$noteView->setWantHiddenTags($gn);
$noteView->setWantCommentsLink(true);
$tn[] = $noteView->getNoteCTree();
}
if (count($tn)) {
$vb["notes"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
return $vb;
}
function e2m_calendar()
{
z1(p());
}
function r($wn)
{
global $_config;
$tn = null;
if (CACHE_FULLLIST and is_file(USER_DIR . CACHE_FILENAME_FULLLIST)) {
$tn = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_FULLLIST)
);
if (Log::$a) {
__log("Retrieving full notes list from cache...");
}
}
if (!is_array($tn)) {
if (Log::$a) {
__log("Retrieving full notes list from database...");
}
sm(
"SELECT `ID`, `Title`, `Stamp`, `LastModified`, `Offset`, `IsDST`, " .
"`IsFavourite`, `IsPublished`, `IsVisible`, `SourceNoteURL`, `OriginalAlias` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df() .
"ORDER BY `Stamp`",
"get full notes list"
);
$h3 = qm();
$tn = w($wn, $h3);
if ($wn) {
if (CACHE_FULLLIST) {
e3(USER_DIR . CACHE_FILENAME_FULLLIST, serialize($tn));
}
}
}
return $tn;
}
function e2m_everything($parameters = [])
{
global $_strings;
$tn = r(true);
$un = count($tn);
$sn = e2l_get_string("pt--n-posts", ["number" => $un]);
$vb = ["title" => $sn, "heading" => $sn];
if (count($tn)) {
$vb["notes-list"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-notes"];
}
return $vb;
}
function e2m_sitemap_xml($parameters = [])
{
global $_config;
$tn = r(false);
if (@$_config["dev_xml_as_text"]) {
header("Content-Type: text/plain");
} else {
header("Content-type: application/xml; charset=utf-8");
}
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' .
"\r\n";
if (count($tn)) {
$in = @$tn[0]["last-modified"];
echo "<url>" . "\r\n";
echo "<loc>" . eq("e2m_frontpage", ["page" => 1]) . "</loc>" . "\r\n";
echo "<lastmod>";
echo gmdate("Y-m-d\TH:i:s\Z", $in[0]);
echo "</lastmod>" . "\r\n";
echo "<changefreq>hourly</changefreq>";
echo "</url>" . "\r\n";
foreach ($tn as $r) {
echo "<url>" . "\r\n";
echo "<loc>";
echo $r["href"];
echo "</loc>" . "\r\n";
echo "<lastmod>";
echo gmdate("Y-m-d\TH:i:s\Z", $r["last-modified"][0]);
echo "</lastmod>" . "\r\n";
echo "</url>" . "\r\n";
}
}
echo "</urlset>" . "\r\n";
die();
}
function t($dn, $jn, $hn)
{
if (is_numeric($jn)) {
$on = y1("t", gmmktime(0, 0, 0, (int) $jn, 1, (int) $dn), oa());
} else {
$on = 0;
}
$pn = cv("start");
$cm = y1("Y", $pn["stamp"], $pn["timezone"]);
$vm = n1("Y", time());
$bm = n1("m", time());
if ((int) $dn == (int) $cm) {
$ym = y1("m", $pn["stamp"], $pn["timezone"]);
} else {
$ym = 1;
}
if ((int) $dn == (int) $vm) {
$bm = n1("m", time());
} else {
$bm = 12;
}
if ((int) $dn == (int) $cm and (int) $jn == (int) $ym) {
$nm = y1("d", $pn["stamp"], $pn["timezone"]);
} else {
$nm = 1;
}
if ((int) $dn == (int) $vm and (int) $jn == (int) $bm) {
$mm = n1("d", time());
} else {
$mm = $on;
}
if (1) {
$fm = u();
for ($gb = $cm; $gb <= $vm; ++$gb) {
$dm = gmmktime(0, 0, 0, 1, 1, (int) $gb);
$sm[$gb] = [
"number" => $gb,
"start-time" => [$dm, oa()],
"href" => eq("e2m_year", ["year" => gmdate("Y", $dm)]),
"this?" => (bool) ($gb == $dn),
"real?" => true,
"fruitful?" => @in_array(gmdate("Y", $dm), $fm),
];
}
$am["years"] = $sm;
}
if (1) {
$qm = i($dn);
for ($gb = 1; $gb <= 12; ++$gb) {
$dm = gmmktime(0, 0, 0, (int) $gb, 1, (int) $dn);
$lm[$gb] = [
"number" => $gb,
"start-time" => [$dm, oa()],
"href" => eq("e2m_month", [
"year" => gmdate("Y", $dm),
"month" => gmdate("m", $dm),
]),
"this?" => (bool) ($gb == $jn),
"real?" => $gb >= $ym and $gb <= $bm,
"fruitful?" => @in_array(gmdate("n", $dm), $qm),
];
}
$am["months"] = $lm;
}
if ($on) {
$zm = o($dn, $jn);
for ($gb = 1; $gb <= $on; ++$gb) {
$dm = gmmktime(0, 0, 0, (int) $jn, (int) $gb, (int) $dn);
$km[$gb] = [
"number" => $gb,
"start-time" => [$dm, oa()],
"href" => eq("e2m_day", [
"year" => gmdate("Y", $dm),
"month" => gmdate("m", $dm),
"day" => gmdate("d", $dm),
]),
"this?" => (bool) ($gb == $hn),
"real?" => $gb >= $nm and $gb <= $mm,
"fruitful?" => @in_array(gmdate("d", $dm), $zm),
];
}
$am["days"] = $km;
}
return $am;
}
function j($dn, $jn = false, $hn = false)
{
$pn = cv("start");
if ($pn === false) {
return false;
}
$xm = y1("Y", $pn["stamp"], $pn["timezone"]);
$em = n1("Y", time());
if ($jn === false) {
return (bool) ($dn >= $xm and $dn <= $em);
} else {
$rm = y1("n", $pn["stamp"], $pn["timezone"]);
$tm = n1("n", time());
if ($hn === false) {
return (bool) ($jn >= 1 and
$jn <= 12 and
($dn > $xm and $dn < $em or
$dn == $xm and $jn >= $rm or
$dn == $em and $jn <= $tm));
} else {
$jm = y1("j", $pn["stamp"], $pn["timezone"]);
$hm = n1("j", time());
if (1) {
return (bool) (checkdate($jn, $hn, $dn) and
($dn > $xm and $dn < $em or
$dn == $xm and $jn > $rm or
$dn == $xm and $jn == $rm and $hn >= $jm or
$dn == $em and $jn < $tm or
$dn == $em and $jn == $tm and $hn <= $hm));
}
}
}
}
function e2__fruitful_neighbours_with_ymd_($gm, $wm = false, $um = false)
{
global $_db, $_config;
list($im, $om) = s1($gm, $wm, $um);
$pm = SECONDS_IN_A_DAY;
if ($um === false) {
$pm = SECONDS_IN_A_MONTH;
}
if ($wm === false) {
$pm = SECONDS_IN_A_YEAR;
}
$cf = $vf = null;
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` < '" .
($om - $pm) .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()) .
"ORDER BY Stamp DESC",
"get previous fruitful neighbour with ymd"
);
while ($bf = mysqli_fetch_array($_db["result"], MYSQLI_ASSOC)) {
list($dn, $jn, $hn) = explode("/", y1("Y/n/j", $bf["Stamp"], ia($bf)));
$yf = $gm * 10000 + ($wm ? $wm * 100 : 0) + ($um ? $um : 0);
$nf = $dn * 10000 + ($wm ? $jn * 100 : 0) + ($um ? $hn : 0);
if ($nf < $yf) {
$cf = gmmktime(0, 0, 0, (int) $jn, (int) $hn, (int) $dn);
break;
}
}
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` > '" .
($im + $pm) .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()) .
"ORDER BY Stamp",
"get next fruitful neighbour with ymd"
);
while ($bf = mysqli_fetch_array($_db["result"], MYSQLI_ASSOC)) {
list($dn, $jn, $hn) = explode("/", y1("Y/n/j", $bf["Stamp"], ia($bf)));
$yf = $gm * 10000 + ($wm ? $wm * 100 : 0) + ($um ? $um : 0);
$nf = $dn * 10000 + ($wm ? $jn * 100 : 0) + ($um ? $hn : 0);
if ($nf > $yf) {
$vf = gmmktime(0, 0, 0, (int) $jn, (int) $hn, (int) $dn);
break;
}
}
return [$cf, $vf];
}
function e2__parameters_with_timestamp_($mf)
{
list(
$parameters["year"],
$parameters["month"],
$parameters["day"],
) = explode("/", gmdate("Y/m/d", $mf));
return $parameters;
}
function w($wn, $ff, $dn = false, $jn = false)
{
$tn = [];
$df = [];
foreach ($ff as $k3 => $zy) {
$r["href"] = eq("e2m_note", ["*note" => $zy]);
$r["time"] = [(int) $zy["Stamp"], ia($zy)];
$r["last-modified"] = [(int) min($zy["LastModified"], time()), ia($zy)];
$r["favourite?"] = (bool) ($zy["IsFavourite"] && $zy["IsPublished"]);
$sf = ff($zy);
$r["draft?"] = $sf === "draft";
$r["scheduled?"] = $sf === "scheduled";
$r["public?"] = $sf === "public";
$r["hidden?"] = $sf === "hidden";
if (
array_key_exists("SourceNoteURL", $zy) and
@$zy["SourceNoteURL"] != ""
) {
$r["href"] = $zy["SourceNoteURL"];
$r["href-original"] = $zy["SourceNoteURL"];
}
if (
$dn and
$jn and
((int) $dn) . "/" . ((int) $jn) ==
y1("Y/n", $zy["Stamp"], ia($zy)) or
$dn and !$jn and (int) $dn == y1("Y", $zy["Stamp"], ia($zy)) or
!$dn and !$jn
) {
$tn[] = $r;
$df[] = str_replace("\n", " ", $zy["Title"]);
}
}
if (Log::$a) {
__log("Will do typography");
}
if ($wn) {
$af = implode("\n", $df);
$af = ay(htmlspecialchars($af, ENT_NOQUOTES, "UTF-8"));
$df = explode("\n", $af);
}
foreach ($tn as $k3 => $x3) {
$tn[$k3]["title"] = $df[$k3];
}
$tn = array_reverse($tn);
return $tn;
}
function u()
{
global $_config;
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()),
"get all notes list years with notes"
);
$h3 = qm();
$qf = [];
foreach ($h3 as $lf) {
$zf = (int) y1("Y", $lf["Stamp"], ia($lf));
$qf[$zf] = true;
}
$qf = array_keys($qf);
sort($qf);
return $qf;
}
function i($gm)
{
global $_config;
list($kf, $xf) = s1($gm);
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` BETWEEN '" .
$kf .
"' AND '" .
$xf .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()),
"get all notes for the year " . $gm . " to list months with notes"
);
$h3 = qm();
$ef = [];
foreach ($h3 as $lf) {
if (((int) $gm) == y1("Y", $lf["Stamp"], ia($lf))) {
$rf = (int) y1("n", $lf["Stamp"], ia($lf));
$ef[$rf] = true;
}
}
$ef = array_keys($ef);
sort($ef);
return $ef;
}
function o($gm, $wm)
{
global $_config;
list($tf, $jf) = s1($gm, $wm);
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` BETWEEN '" .
$tf .
"' AND '" .
$jf .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()),
"get all notes for the month " .
$wm .
" of the year " .
$gm .
" to list days with notes"
);
$h3 = qm();
$hf = [];
foreach ($h3 as $lf) {
if (
((int) $gm) . "/" . ((int) $wm) ==
y1("Y/n", $lf["Stamp"], ia($lf))
) {
$gf = (int) y1("j", $lf["Stamp"], ia($lf));
$hf[$gf] = true;
}
}
$hf = array_keys($hf);
sort($hf);
return $hf;
}
function p()
{
$wf = cv("end");
return eq("e2m_day", [
"year" => y1("Y", $wf["stamp"], $wf["timezone"]),
"month" => y1("m", $wf["stamp"], $wf["timezone"]),
"day" => y1("d", $wf["stamp"], $wf["timezone"]),
]);
}
function cv($uf)
{
global $_config;
$if_ = "p1";
$gn = ys();
if (!$gn) {
$if_ = "p1v1";
}
$of = USER_DIR . CACHES_DIRNAME . $uf . "-stamp-" . $if_ . ".e2time.psa";
if (CACHE_EDGE_TIMEINFO and is_file($of)) {
$vb = @unserialize(file_get_contents($of));
}
if (is_array(@$vb)) {
return $vb;
} else {
$vb = ["stamp" => time(), "timezone" => pa()];
$pf = $uf == "end" ? " DESC" : "";
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` <= '" .
time() .
"' " .
df($gn) .
"ORDER BY `Stamp`" .
$pf .
" LIMIT 1",
"get " . $uf . " timestamp"
);
$h3 = qm();
if (count($h3)) {
$vb = ["stamp" => $h3[0]["Stamp"], "timezone" => ia($h3[0])];
if (CACHE_EDGE_TIMEINFO) {
e3($of, serialize($vb));
}
return $vb;
}
return $vb;
}
}
function vv($url, $c2 = false)
{
if ($_SERVER["HTTP_USER_AGENT"] === E2_UA_STRING) {
if (Log::$a) {
__log("Spawn not allowed when requested by Aegea itself");
}
return false;
}
if (Log::$a) {
__log(
"Spawn: Curl " . $url . " using " . ($c2 ? "post" : "get") . "..."
);
}
if (function_exists("curl_init")) {
$v2 = curl_init();
$b2 = !ini_get("open_basedir");
$b2 = ($b2 and !$c2);
curl_setopt_array($v2, [
CURLOPT_URL => $url,
CURLOPT_POST => $c2,
CURLOPT_POSTREDIR => false,
CURLOPT_POSTFIELDS => "",
CURLOPT_CONNECTTIMEOUT => 300,
CURLOPT_TIMEOUT => 1,
CURLOPT_MAXREDIRS => 1,
CURLOPT_COOKIE => fs(),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => $b2,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_USERAGENT => E2_UA_STRING,
]);
$content = curl_exec($v2);
$y2 = curl_errno($v2);
$n2 = curl_error($v2);
$m2 = curl_getinfo($v2);
curl_close($v2);
if (Log::$a) {
__log(
"Spawn: Curl returns: [" .
print_r($m2, true) .
"] [" .
$content .
"], (errno=" .
$y2 .
", errstr=" .
$n2 .
")..."
);
}
return $m2;
} else {
if (Log::$a) {
__log("Spawn: Curl functions are not available");
}
}
}
function e2_check_timeout()
{
static $f2;
if (is_null($f2)) {
$d2 = ini_get("max_execution_time");
if ($d2) {
$f2 = time() + $d2 - 5;
} else {
$f2 = 0;
}
}
return $f2 == 0 ? true : $f2 >= time();
}
function e2_write_dump_header($s2)
{
$m2 =
'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' .
PHP_EOL .
"SET AUTOCOMMIT=0;" .
PHP_EOL .
"START TRANSACTION;" .
PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;" .
PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;" .
PHP_EOL .
"/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;" .
PHP_EOL .
"/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;" .
PHP_EOL .
"/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;" .
PHP_EOL .
"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;" .
PHP_EOL .
"/*!40101 SET NAMES utf8 */;" .
PHP_EOL .
"/*!50503 SET NAMES utf8mb4 */;" .
PHP_EOL .
"";
fwrite($s2, $m2);
return true;
}
function e2_write_dump_footer($s2)
{
$a2 = "COMMIT;" . PHP_EOL;
$a2 .=
"/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;" .
PHP_EOL .
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;" .
PHP_EOL .
"/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;" .
PHP_EOL .
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;" .
PHP_EOL .
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;" .
PHP_EOL .
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;" .
PHP_EOL;
fwrite($s2, $a2);
return true;
}
function e2_get_table_definition($q2, $l2)
{
$z2 = null;
$h3 = mysqli_query($q2, "SHOW CREATE TABLE `{$l2}`");
if ($h3) {
$k2 = mysqli_fetch_array($h3);
$z2 = $k2["Create Table"];
}
return $z2;
}
function e2_write_table_definition($s2, $q2, $l2)
{
$x2 = e2_get_table_definition($q2, $l2);
if (e2_check_timeout() && $x2) {
fwrite($s2, $x2);
fwrite($s2, ";");
fwrite($s2, PHP_EOL . PHP_EOL);
return true;
}
return false;
}
function e2_get_table_data($q2, $l2, $t3, $limit)
{
$e2_ = "SELECT * FROM `{$l2}` LIMIT {$t3}, {$limit}";
$h3 = mysqli_query($q2, $e2_);
if (!$h3) {
return false;
}
$r2 = "";
$t2 = "INSERT INTO `{$l2}` VALUES";
while ($j2 = mysqli_fetch_row($h3)) {
$h2 = [];
foreach ($j2 as $vv) {
$h2[] = is_null($vv)
? "NULL"
: "'" . mysqli_real_escape_string($q2, $vv) . "'";
}
$r2 .= $t2 . "(" . join(", ", $h2) . ");" . PHP_EOL;
}
return $r2;
}
function e2_table_disable_keys($l2)
{
return "ALTER TABLE `{$l2}` DISABLE KEYS;" . PHP_EOL;
}
function e2_table_enable_keys($l2)
{
return "ALTER TABLE `{$l2}` ENABLE KEYS;" . PHP_EOL;
}
function e2_get_total_records($q2, $l2)
{
$k3 = mysqli_fetch_row(mysqli_query($q2, "SELECT COUNT(*) FROM `{$l2}`"));
return $k3[0];
}
function e2_backup_select_chuck_size_for_table_($l2)
{
$limit = 5000;
if (substr($l2, -7) === "Actions") {
$limit = 50000;
}
if (substr($l2, -7) === "Aliases") {
$limit = 20000;
}
if (substr($l2, -7) === "NotesKeywords") {
$limit = 50000;
}
if (Log::$a) {
__log("Backup: chunk size " . (int) $limit);
}
return $limit;
}
function e2_write_table_data($s2, $q2, $l2, $subset)
{
$g2 = e2_get_total_records($q2, $l2);
$t3 = 0;
$limit = e2_backup_select_chuck_size_for_table_($l2);
$h3 = true;
$w2 = 20000;
$u2 = 30;
if ($g2) {
$i2 = e2_table_disable_keys($l2);
fwrite($s2, $i2);
}
$r2 = "INSERT INTO `{$l2}` VALUES";
$o2 = $g2;
while ($o2 > 0) {
$e2_ = "SELECT * FROM `{$l2}` ";
if ((int) $subset > 0) {
$e2_ .= "WHERE `SubsetID` = {$subset} ";
}
$e2_ .= "ORDER BY `ID` LIMIT {$t3}, {$limit}";
$h3 = mysqli_query($q2, $e2_);
$p2 = mysqli_num_rows($h3);
if (!$h3 || !e2_check_timeout()) {
$h3 = false;
break;
}
$cd = [];
$vd = 0;
$bd = 0;
while ($j2 = mysqli_fetch_row($h3)) {
if (!e2_check_timeout()) {
$h3 = false;
break;
}
$p2--;
$fb = [];
foreach ($j2 as $vv) {
$fb[] = is_null($vv)
? "NULL"
: "'" . mysqli_real_escape_string($q2, $vv) . "'";
}
$zb = "(" . join(", ", $fb) . ")";
$vd += strlen($zb);
$cd[] = $zb;
$bd++;
if ($vd >= $w2 || $bd >= $u2 || $p2 == 0) {
$e2_ = $r2 . join(", ", $cd) . ";";
fwrite($s2, $e2_);
fwrite($s2, PHP_EOL);
$vd = 0;
$bd = 0;
$cd = [];
}
}
$t3 += $limit;
$o2 -= $limit;
}
if ($g2) {
$yd = e2_table_enable_keys($l2);
fwrite($s2, $yd);
}
return $h3;
}
function e2_backup($q2, $nd, $subset, $md)
{
$fd = tmpfile();
e2_write_dump_header($fd);
if (Log::$a) {
__log("Backup: wrote header");
}
$dd = true;
foreach ($nd as $l2) {
if ((int) $subset > 0) {
if (Log::$a) {
__log("Backup: table " . $l2 . ", subset " . $subset);
}
} else {
if (Log::$a) {
__log("Backup: table " . $l2 . ", all subsets");
}
}
$sd = e2_write_table_definition($fd, $q2, $l2);
if (Log::$a) {
__log("Backup: wrote table definition with result " . @(int) $sd);
}
$ad = e2_write_table_data($fd, $q2, $l2, $subset);
if (Log::$a) {
__log("Backup: wrote table data with result " . @(int) $ad);
}
$dd = $sd && $ad;
if ($dd === false) {
break;
}
}
if (Log::$a) {
__log("Backup: wrote data with running == " . (int) $dd);
}
if ($dd) {
e2_write_dump_footer($fd);
fseek($fd, 0);
$s2 = fopen($md, "w+");
while ($dd && ($zb = fread($fd, 1024))) {
if (e2_check_timeout()) {
fwrite($s2, $zb);
} else {
$dd = false;
}
}
fclose($s2);
}
fclose($fd);
return $dd;
}
function xv()
{
global $settings, $_lang, $_config, $_strings;
if (Log::$a) {
__log("Blog information");
}
$qd["author"] = htmlspecialchars(rv(), ENT_NOQUOTES, "UTF-8");
if (array_key_exists("blog_subtitle", $settings)) {
$ld = zy($settings["blog_subtitle"], "full");
$zd = $ld["text-final"];
$qd["subtitle"] = $zd;
$qd["subtitle-format-info"] = $ld["meta"];
m2(@$ld["meta"]["links-required"]);
}
$qd["title"] = htmlspecialchars(ev(), ENT_NOQUOTES, "UTF-8");
$qd["userpic-set?"] = false;
$qd["userpic-changeable?"] = ys();
if ($qd["userpic-href"] = tv()) {
$qd["userpic-set?"] = true;
$qd["userpic-large-href"] = tv("large");
$qd["userpic-square-href"] = tv("square");
$qd["userpic-changeable-href"] = $qd["userpic-href"];
} else {
unset($qd["userpic-href"]);
}
if (ys()) {
$qd["userpic-upload-action"] = eq("e2j_userpic_upload");
$qd["userpic-remove-action"] = eq("e2j_userpic_remove");
}
$qd["href"] = eq("e2m_frontpage", ["page" => 1]);
$qd["rss-href"] = eq("e2m_rss");
$qd["jsonfeed-href"] = eq("e2m_json");
$qd["language"] = $_lang;
$qd["show-follow-button?"] = false;
$qd["license-expired?"] = false;
$xd = [time(), pa()];
$ed = n1("Y", $xd[0]);
$qd["now"] = $xd;
$rd = $ed;
$td = cv("start");
if (array_key_exists("stamp", $td)) {
$rd = n1("Y", $td["stamp"]);
$qd["start-time"] = [(int) $td["stamp"], $td["timezone"]];
}
$jd = false;
$hd = nf(true, true);
if ($hd !== null) {
if (ys()) {
$gd = nf(true, false);
if ($gd !== null) {
$jd = $hd + $gd == 0;
}
} else {
$jd = $hd == 0;
}
}
$qd["notes-count"] = (int) $hd;
if ($qd["notes-count"] > 0) {
$qd["selected-href"] = eq("e2m_favourites", ["page" => 1]);
$qd["most-commented-href"] = eq("e2m_most_commented", ["page" => 1]);
$qd["popular-href"] = eq("e2m_popular", ["page" => 1]);
$qd["calendar-href"] = p();
$qd["random-note-href"] = sf();
}
$qd["virgin?"] = $jd;
$wd = $_config["years_range_separator"]
? $_config["years_range_separator"]
: $_strings["gs--range-separator"];
$qd["years-range"] = $rd . ($rd == $ed ? "" : $wd . $ed);
if (AeEnv::$w) {
$qd["parent-site-href"] = substr(
AeEnv::$w,
(int) strpos("/", AeEnv::$w)
);
}
return $qd;
}
function ev()
{
global $settings, $_strings;
if (
array_key_exists("blog_title", $settings) and
trim($settings["blog_title"]) != ""
) {
return trim($settings["blog_title"]);
} else {
return $_strings["e2--default-blog-title"];
}
}
function rv()
{
global $settings, $_strings;
if (
array_key_exists("author", $settings) and
trim($settings["author"]) != ""
) {
return trim($settings["author"]);
} else {
return $_strings["e2--default-blog-author"];
}
}
function tv($size = "")
{
global $_config;
$ud = false;
$id = $_config["path_media"] . USERPIC_DIRNAME;
if (is_file($id . "[email protected]")) {
$ud = "[email protected]";
} elseif (is_file($id . "[email protected]")) {
$ud = "[email protected]";
}
if ($size == "large" and is_file($id . "[email protected]")) {
$ud = "[email protected]";
} elseif ($size == "square" and is_file($id . "[email protected]")) {
$ud = "[email protected]";
}
if ($ud === false) {
return false;
}
$od = $id . $ud;
$pd = AeEnv::$o . USERPIC_DIRNAME . $ud;
$cs = stat($od);
if ($cs["mtime"]) {
$pd .= "?" . $cs["mtime"];
}
return $pd;
}
function jv()
{
global $_config, $_stopwatch, $vs;
$bs = round(dq() - $_stopwatch, 3);
return [
"show?" => $_config["display_stat"] > (int) !ys(),
"generation-time" => str_replace(".", ",", $bs),
"peak-memory-mb" => str_replace(
".",
",",
round((memory_get_peak_usage() / 1024 / 1024) * 100) / 100
),
"db-query-count" => (int) @$vs,
];
}
function e2m_info()
{
global $settings, $_template;
if (!isset($_template)) {
kf();
}
$ys = [
"E2_VERSION" => E2_VERSION,
"E2_RELEASE" => E2_RELEASE,
"E2_UA_STRING" => E2_UA_STRING,
"E2_EDITION" => defined("E2_EDITION") ? E2_EDITION : "0",
"---",
"PHP_VERSION" => PHP_VERSION,
"---",
"installed" => yn() !== null,
"server_name" => AeEnv::$server,
"folder_on_server" => AeEnv::$w,
"---",
"default formatter" => DEFAULT_FORMATTER,
"---",
"theme" => $settings["template"],
"---",
"Olba name" => $_template["name"],
"Olba stack" => $_template["stack"],
"---",
"Neasden" => substr(
md5(file_get_contents("system/library/neasden/Interpreter.php")),
0,
4
),
"---",
];
echo "<pre>";
foreach ($ys as $k3 => $x3) {
if ($x3 == "---") {
echo "\n";
continue;
}
echo str_pad($k3, 24);
echo '\'';
print_r($x3);
echo '\'';
echo "\n";
}
echo "</pre>";
die();
}
function hv($s)
{
global $_config;
if (@$_config["broadcast_url"] and !$s["IsExternal"]) {
if ($_config["log_broadcast"]) {
Log::$a = true;
if (Log::$a) {
qn("broadcast");
}
}
if (Log::$a) {
__log("Broadcast-async note: " . $s["Title"]);
}
$url = eq("e2m_note_broadcast", ["*note" => $s]);
if (Log::$a) {
__log("Broadcast will spawn url: " . $url);
}
vv($url);
}
}
function gv($ns)
{
global $_config;
if (!$ns) {
return false;
}
$url = $_config["broadcast_url"];
$url .= "?src=" . urlencode($ns);
if ($_config["log_broadcast"]) {
Log::$a = true;
if (Log::$a) {
qn("broadcast");
}
}
if (Log::$a) {
__log("Broadcast: Curl " . $url . "...");
}
if (function_exists("curl_init")) {
$v2 = curl_init();
$b2 = !ini_get("open_basedir");
curl_setopt_array($v2, [
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 300,
CURLOPT_TIMEOUT => 1,
CURLOPT_MAXREDIRS => 1,
CURLOPT_COOKIE => fs(),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => $b2,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_USERAGENT => E2_UA_STRING,
]);
$content = curl_exec($v2);
$y2 = curl_errno($v2);
$n2 = curl_error($v2);
$m2 = curl_getinfo($v2);
curl_close($v2);
if (Log::$a) {
__log(
"Broadcast: Curl returns: [" .
print_r($m2, true) .
"] [" .
$content .
"], (errno=" .
$y2 .
", errstr=" .
$n2 .
")..."
);
}
if ($y2 === 0) {
return true;
}
} else {
if (Log::$a) {
__log("Spawn: Curl functions are not available");
}
}
return false;
}
function wv($s)
{
if (!$s) {
return false;
}
$ns = eq("e2m_note_json", ["*note" => $s]);
return gv($ns);
}
function e2m_note_broadcast($parameters = [])
{
global $_config;
if (@$_config["broadcast_url"]) {
if (array_key_exists("*note", $parameters)) {
$ns = eq("e2m_note_json", ["*note" => $parameters["*note"]]);
} elseif (array_key_exists("alias", $parameters)) {
$ns = eq("e2m_note_json", ["alias" => $parameters["alias"]]);
}
if (gv($ns)) {
die("Broadcasted.");
} else {
die("Could not broadcast.");
}
} else {
return e2m_error404();
}
}
function e2_cache_filename_with_id_($ey, $if_)
{
return str_replace("*", $ey, $if_);
}
function e2_note_cache_filename_with_id_($ey)
{
return e2_cache_filename_with_id_($ey, USER_DIR . CACHE_FILENAMES_NOTES);
}
function e2_drop_caches_for_note_($note_id, $ms)
{
if (is_numeric($note_id)) {
if (Log::$a) {
__log("Caches: Drop caches for note id " . $note_id);
}
@unlink(e2_note_cache_filename_with_id_($note_id));
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments"));
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments-author"));
} else {
bq(USER_DIR . CACHE_FILENAMES_NOTES);
bq(USER_DIR . CACHE_FILENAMES_NOTES_COMMENTS);
bq(USER_DIR . CACHE_FILENAMES_NOTES_COMMENTS_AUTHOR);
}
vb();
if ($ms !== false) {
bb();
bq(USER_DIR . CACHE_FILENAMES_NOTES_RELATED);
bq(USER_DIR . CACHE_FILENAMES_POPULAR_WITH_TAG);
bq(USER_DIR . CACHE_FILENAMES_TAG);
bq(USER_DIR . CACHE_FILENAMES_TAG_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_POPULAR);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE_FEED);
@unlink(USER_DIR . CACHE_FILENAME_FULLLIST);
@unlink(USER_DIR . CACHE_FILENAME_TAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_FULL);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR_FULL);
}
if ($ms !== true) {
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
}
@unlink(USER_DIR . CACHE_FILENAME_LASTMODIFIEDS);
}
function e2_drop_caches_for_tag_($fs)
{
if (is_numeric($fs)) {
@unlink(
e2_cache_filename_with_id_($fs, USER_DIR . CACHE_FILENAMES_TAG)
);
@unlink(
e2_cache_filename_with_id_(
$fs,
USER_DIR . CACHE_FILENAMES_TAG_AUTHOR
)
);
} else {
bq(USER_DIR . CACHE_FILENAMES_TAG);
bq(USER_DIR . CACHE_FILENAMES_TAG_AUTHOR);
}
@unlink(USER_DIR . CACHE_FILENAME_FAVTAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_FULL);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR_FULL);
}
function cb()
{
if (Log::$a) {
__log("Caches: Drop notes caches");
}
e2_drop_caches_for_note_(null, null);
}
function vb()
{
if (Log::$a) {
__log("Caches: Drop notes counts cache");
}
bq(USER_DIR . CACHE_FILENAMES_NOTES_COUNTS);
}
function bb()
{
if (Log::$a) {
__log("Caches: Drop egde time info cache");
}
bq(USER_DIR . CACHE_FILENAMES_EDGE_TIMEINFO);
}
function e2_drop_all_kinds_of_cache()
{
if (Log::$a) {
__log("Caches: Drop all kinds of caches");
}
bq(USER_DIR . CACHES_DIRNAME . "*");
return true;
}
function e2m_comment($parameters = [])
{
z1(eq("e2m_note", $parameters));
}
function e2m_comment_edit($parameters = [])
{
return yb("edit", $parameters);
}
function yb($ds, $parameters = [])
{
global $_strings;
$ss = $as_ = $_strings["pt--new-comment"];
$qs = "new";
if ($ds == "edit") {
$ls = e2_commentrec_with_parameters_($parameters);
$zs = $_strings["fb--save-changes"];
$zy = $ls["noterec"];
$ss = $as_ = $_strings["pt--edit-comment"];
$ks = mb($zy, $ls, $parameters["comment-number"]);
if (!$ls) {
return e2m_error404();
}
$xs = [
".note-id" => $ls["NoteID"],
".comment-id" => $ls["ID"],
".comment-number" => $parameters["comment-number"],
".already-subscribed?" => false,
".gip" => $ls["GIP"],
"create:edit?" => false,
"form-action" => eq("e2s_comment_process"),
"submit-text" => $zs,
"show-subscribe?" => true,
"subscribe?" => (bool) $ls["IsSubscriber"],
"name" => htmlspecialchars($ls["AuthorName"], ENT_COMPAT, "UTF-8"),
"email" => htmlspecialchars(
$ls["AuthorEmail"],
ENT_COMPAT,
"UTF-8"
),
"text" => htmlspecialchars($ls["Text"], ENT_COMPAT, "UTF-8"),
"email-field-name" => a(),
"email-fields-revealed?" => true,
];
if ("" != trim($ls["IP"])) {
$xs["ip"] = $ls["IP"];
}
}
$vb = [
"title" => $ss,
"heading" => $as_,
"form" => "form-comment",
"form-comment" => $xs,
];
if (!empty($ks)) {
$vb["comments"] = ["each" => ["only" => $ks]];
}
return $vb;
}
function e2m_comment_reply($parameters = [])
{
global $_strings;
$ls = e2_commentrec_with_parameters_($parameters);
if (!$ls) {
return e2m_error404();
}
$zy = $ls["noterec"];
$ks = mb($zy, $ls, $parameters["comment-number"]);
$ks["replying?"] = (bool) true;
$es = ($ls["Reply"] == "" or !$ls["IsReplyVisible"]);
$ss = $es
? $_strings["pt--reply-to-comment"]
: $_strings["pt--edit-reply-to-comment"];
$rs = [
".note-id" => $zy["ID"],
".comment-id" => $ls["ID"],
".reply-action" => $es ? "new" : "edit",
"form-action" => eq("e2s_comment_edit_reply"),
"submit-text" => $es
? $_strings["fb--publish"]
: $_strings["fb--save-changes"],
"create:edit?" => (bool) $es,
"reply-text" => htmlspecialchars($ls["Reply"], ENT_COMPAT, "UTF-8"),
"emailing-possible?" => MAIL_ENABLED,
"mail-back?" => (bool) $es,
];
return [
"title" => $ss,
"heading" => $ss,
"comments" => ["each" => ["only" => $ks]],
"form" => "form-comment-reply",
"form-comment-reply" => $rs,
];
}
function e2m_comment_delete($parameters = [])
{
global $_config;
$ls = e2_commentrec_with_parameters_($parameters);
$note_id = $ls["NoteID"];
if (!$ls) {
return e2m_error404();
}
e2_drop_caches_for_note_($note_id, true);
@unlink(USER_DIR . "/last-comment.psa");
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
((int) $ls["ID"]) .
"'"
);
k1();
}
function e2m_comment_reply_delete($parameters = [])
{
global $_strings, $settings, $_config;
$ls = e2_commentrec_with_parameters_($parameters);
if (!$ls) {
return e2m_error404();
}
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Comments` SET " .
"`Reply`='', " .
"`IsReplyFavourite`='0' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
((int) $ls["ID"])
);
k1();
}
function e2m_unsubscribe($parameters)
{
global $_strings, $_config;
$pf = "ORDER BY `ID` DESC";
$ts = false;
$zy = $parameters["*note"];
$note_id = $zy["ID"];
$js = $parameters["unsubscribe-email"];
$hs = $parameters["unsubscribe-key"];
$js = str_replace(" ", "+", $js);
if ($note_id) {
sm(
"SELECT `ID`, `Stamp` FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
$note_id .
" " .
"AND `IsSubscriber`=1 " .
"AND `AuthorEmail`='" .
lm($js) .
"' " .
$pf,
"get subscribers comments ids"
);
$h3 = qm();
if (count($h3) < 1) {
$vb["unsubscribe"]["error-message"] =
$_strings["gs--you-are-not-subscribed"];
} else {
$gs = @$h3[0];
$ws = md5($gs["ID"] . $gs["Stamp"] . "x");
if ($hs == $ws) {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Comments` " .
"SET `IsSubscriber`=0 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
$note_id .
" " .
"AND `AuthorEmail` = '" .
lm($js) .
"'",
"unsubscribe"
);
$ts = true;
$vb["unsubscribe"]["note-title"] = ay(
htmlspecialchars($zy["Title"], ENT_COMPAT, "UTF-8")
);
$vb["unsubscribe"]["note-href"] = eq("e2m_note", [
"*note" => $zy,
]);
}
if (!$ts) {
$vb["unsubscribe"]["error-message"] =
$_strings["gs--unsubscription-didnt-work"];
}
}
} else {
$vb["unsubscribe"]["error-message"] = $_strings["gs--post-not-found"];
}
if ($ts) {
$ss = $_strings["pt--unsubscription-done"];
} else {
$ss = $_strings["pt--unsubscription-failed"];
}
$vb["unsubscribe"]["success?"] = $ts;
$vb["title"] = $ss;
$vb["heading"] = $ss;
return $vb;
}
function e2m_comment_flag($parameters)
{
nb($parameters);
z1(eq("e2m_note", $parameters));
}
function e2s_comment_flag_ajax($parameters)
{
g1([
"flag-name" => "comment",
"candy-name" => "e2s_comment_flag_ajax",
"parameters" => $parameters,
"flipping-function" => function () use ($parameters) {
nb($parameters);
},
"redirect-candy" => "e2m_note",
]);
}
function nb($parameters)
{
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_note", $parameters));
}
od();
$ls = e2_commentrec_with_parameters_($parameters);
$note_id = $ls["NoteID"];
if (!$ls) {
throw new AeException("Comment record not cound from parameters");
}
e2_drop_caches_for_note_($note_id, true);
fm(bl(), "Comments", [
"ID" => $ls["ID"],
$parameters["flag"] => (int) ($parameters["value"] == 1),
]);
}
function e2s_comment_process()
{
global $_strings;
$us = true;
$is = "";
try {
$note_id = rb();
} catch (AeFormIncompleteException $e) {
hb($_strings["er--name-email-text-required"], E2E_USER_ERROR);
z1(eq("e2m_note", ["*note" => wm($e->note_id)]));
} catch (AeFormNoteNotCommentableException $e) {
$us = false;
$os = $_strings["gs--comment-post-not-commentable"];
$ps = $_strings["gs--comment-post-not-commentable-description"];
$is = $e->comment_text;
} catch (AeFormDuplicateCommentException $e) {
$us = false;
$os = $_strings["gs--comment-double-post"];
$ps = $_strings["gs--comment-double-post-description"];
$is = $e->comment_text;
} catch (AeFormCommentTooLongException $e) {
$us = false;
$os = $_strings["gs--comment-too-long"];
$ps = $_strings["gs--comment-too-long-description"];
$is = $e->comment_text;
} catch (AeFormCommentIsSpamSuspectException $e) {
$us = false;
$os = $_strings["gs--comment-spam-suspect"];
$ps = $_strings["gs--comment-spam-suspect-description"];
$is = $e->comment_text;
}
if ($us) {
if ($note_id) {
z1(eq("e2m_note", ["*note" => wm($note_id)]));
} else {
z1();
}
} else {
$vb["title"] = $os;
$vb["heading"] = $os;
$vb["form"] = "form-unaccepted-comment";
$vb["form-unaccepted-comment"] = [
"reason" => $ps,
"text" => @htmlspecialchars($is, ENT_COMPAT, "UTF-8"),
];
return $vb;
}
die();
}
function e2s_comment_edit_reply()
{
global $_config;
od();
$ca = @$_POST["text"];
if (trim($ca) == "") {
$ca = "";
}
$note_id = @$_POST["note-id"];
$zy = wm($note_id);
$qs = @$_POST["comment-id"];
$ls = fb($qs);
$va = isset($_POST["mail-back"]);
$ba = time();
if (@$_POST["reply-action"] == "new") {
$ya = time();
}
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments"));
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments-author"));
if ($ls) {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Comments` SET " .
"`Reply`='" .
lm($ca) .
"', " .
(isset($ya) ? "`ReplyStamp`='" . $ya . "', " : "") .
"`ReplyLastModified`='" .
$ba .
"', " .
"`IsReplyVisible`='1' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
((int) $qs),
"update comment reply"
);
$na = eq("e2m_note", ["*note" => $zy]);
if ($va and $ca != "") {
$ma["comment-time"] = [$ls["Stamp"], pa()];
$ma["commenter"] = $ls["AuthorName"];
$ma["commenter-email"] = $ls["AuthorEmail"];
$ma["comment-text"] = $ls["Text"];
$ma["note-title"] = ay($zy["Title"]);
$ma["reply-time"] = [time(), pa()];
$ma["blog-author"] = rv();
$ma["note-href"] = $na;
$ma["comment-href"] = $na;
$ma["reply-text"] = $ca;
if (1) {
$fa = kn("comment-reply", $ma);
$da = e2l_get_string("em--comment-reply", $ma);
$sa = $ls["AuthorEmail"];
$aa = "From: " . xn();
en($sa, $da, $fa, $aa);
}
if (1) {
unset($ma["commenter-email"]);
$aa = "From: " . xn();
foreach (kb($zy, $ls["AuthorEmail"]) as $qa) {
$la = $qa["AuthorEmail"];
$za = md5($qa["ID"] . $qa["Stamp"] . "x");
$ma["unsubscribe-href"] = eq("e2m_unsubscribe", [
"*note" => $zy,
"unsubscribe-email" => $la,
"unsubscribe-key" => $za,
]);
$sa = $la;
$fa = kn("comment-reply-to-public", $ma);
$da = e2l_get_string(
"em--comment-reply-to-public-subject",
$ma
);
en($sa, $da, $fa, $aa);
}
}
}
z1($na);
} else {
k1();
}
die();
}
function mb($zy, $ls, $ka)
{
global $_config;
if (Log::$a) {
__log("Package comment " . $ls["ID"] . "...");
}
if ($zy === null) {
$zy = wm($ls["NoteID"]);
}
$ma["number"] = $ka;
$xa = !empty($ls["IsGIPUsed"]);
$ma["gip-used?"] = $xa;
$ma["gip"] = $ma["gip-used?"] ? $ls["GIP"] : "";
$ma["name"] = htmlspecialchars($ls["AuthorName"], ENT_NOQUOTES, "UTF-8");
$ma["userpic-set?"] = false;
if ($xa) {
$ea = AVATARS_DIRNAME . $ls["GIP"] . "-" . $ls["GIPAuthorID"] . ".jpg";
if (is_file($_config["path_media"] . $ea)) {
$ma["userpic-set?"] = true;
$ma["userpic-href"] = AeEnv::$o . $ea;
}
}
$ma["name-href"] = "";
if (
$xa and
($ra = gy($ls["GIP"], $ls["GIPAuthorID"], $ls["AuthorProfileLink"]))
) {
$ma["name-href"] = $ra;
}
if (ys()) {
$ma["email"] = htmlspecialchars(
$ls["AuthorEmail"],
ENT_NOQUOTES,
"UTF-8"
);
if ("" != trim($ls["IP"])) {
$ma["ip"] = $ls["IP"];
}
}
$ma["author-name"] = rv();
$ma["new?"] = false;
$ma["important?"] = (bool) $ls["IsFavourite"];
$ma["reply-visible?"] = (bool) ($ls["IsVisible"] && $ls["IsReplyVisible"]);
$ma["reply-important?"] = (bool) $ls["IsReplyFavourite"];
$ma["spam-suspect?"] = (bool) $ls["IsSpamSuspect"];
$ta = [(int) $ls["Stamp"], ia($zy)];
$ma["time"] = $ta;
$ma["last-modified"] = $ta;
if ($ls["LastModified"]) {
$ma["last-modified"] = [(int) $ls["LastModified"], ia($zy)];
}
if ($ls["ReplyStamp"]) {
$ma["reply-time"] = [(int) $ls["ReplyStamp"], ia($zy)];
}
if ($ls["ReplyLastModified"]) {
$ma["reply-last-modified"] = [(int) $ls["ReplyLastModified"], ia($zy)];
}
if (ys()) {
$ma["subscriber?"] = (bool) $ls["IsSubscriber"];
$ma["new?"] = (bool) $ls["IsNew"];
$ma["first-new?"] = false;
if (!@$_config["read_only"]) {
$ma["important-toggle-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsFavourite",
"value" => !$ls["IsFavourite"],
]);
$ma["reply-important-toggle-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsReplyFavourite",
"value" => !$ls["IsReplyFavourite"],
]);
$ma["edit-href"] = eq("e2m_comment_edit", [
"*note" => $zy,
"comment-number" => $ka,
]);
$ma["removed-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsVisible",
"value" => 0,
]);
$ma["removed-reply-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsReplyVisible",
"value" => 0,
]);
$ma["replaced-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsVisible",
"value" => 1,
]);
$ma["replaced-reply-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsReplyVisible",
"value" => 1,
]);
$ja = eq("e2m_comment_reply", [
"*note" => $zy,
"comment-number" => $ka,
]);
if ($ls["Reply"] == "" or !$ls["IsReplyVisible"]) {
$ma["reply-href"] = $ja;
} else {
$ma["edit-reply-href"] = $ja;
}
}
}
if (mb_strlen((string) @$ls["Text"]) > $_config["max_comment_length"]) {
$ls["Text"] = mb_substr($ls["Text"], 0, $_config["max_comment_length"]);
}
$ha = $zy["FormatterID"] === "raw" ? "neasden" : $zy["FormatterID"];
$ld = ly($ha, $ls["Text"], "simple");
$ma["text"] = $ld["text-final"];
$ma["reply"] = "";
$ma["replying?"] = (bool) false;
$ma["replied?"] =
(bool) (trim((string) @$ls["Reply"]) != "" && $ls["IsReplyVisible"]);
if ((string) $ls["Reply"] !== "") {
$ld = ly($zy["FormatterID"], $ls["Reply"], "full");
$ma["reply"] = $ld["text-final"];
}
if (Log::$a) {
__log("Comments: done");
}
return $ma;
}
function fb($ey)
{
global $_config;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
$ey .
"'"
);
$kb = qm();
if (count($kb) > 0) {
return $kb[0];
} else {
return false;
}
}
function db($s)
{
global $_strings, $_config, $settings;
if (@$_config["read_only"]) {
return null;
}
if (!xb($s)) {
return null;
}
$ga = ky();
if (!count($ga) and !empty($settings["comments"]["require_gip"])) {
return null;
}
$wa = (string) @$_COOKIE[x1("commenter_name")];
$ua = (string) @$_COOKIE[x1("commenter_email")];
$ia = (string) @$_COOKIE[x1("commenter_ph")];
$oa = false;
if ($ua and $ia) {
foreach (kb($s) as $qa) {
$ws = md5($qa["ID"] . $qa["Stamp"] . "x");
if ($qa["AuthorEmail"] == $ua and $ia == $ws) {
$oa = true;
break;
}
}
}
$zs = $_strings["fb--submit"];
$nn = q();
$xs = [
".note-id" => $s["ID"],
".comment-id" => "new",
".already-subscribed?" => (bool) $oa,
"cookie-name" => z($s["ID"]),
"cookie-value" => k(),
"email-field-name" => a(),
"nospam-field-name-part-1" => substr($nn, 0, 4),
"nospam-field-name-part-2" => substr($nn, 4),
"create:edit?" => true,
"form-action" => eq("e2s_comment_process"),
"submit-text" => $zs,
"show-subscribe?" => (bool) !$oa,
"emailing-possible?" => MAIL_ENABLED,
"subscribe?" => (bool) $oa,
"subscription-status" => $oa
? $_strings["gs--you-are-already-subscribed"]
: "",
"name" => htmlspecialchars($wa, ENT_COMPAT, "UTF-8"),
"email" => htmlspecialchars($ua, ENT_COMPAT, "UTF-8"),
"text" => "",
"email-comments-enabled?" => empty(
$settings["comments"]["require_gip"]
),
"gips" => [],
];
$pa = false;
$c1 = "";
foreach ($ga as $v1) {
if (!is_file(SYSTEM_DIR . "gips/" . $v1 . ".json")) {
continue;
}
$b1 = ty($v1);
$xs["gips"][$v1] = ry($v1);
if ($b1) {
$pa = true;
$y1 = wy($v1);
$c1 = $y1["GIP"];
$xs["name"] = htmlspecialchars(
$y1["AuthorName"],
ENT_COMPAT,
"UTF-8"
);
}
}
if (!$xs["email-comments-enabled?"] and !count($xs["gips"])) {
return false;
}
$n1 = count($xs["gips"]) === 0;
$xs["email-comments-only?"] = $n1;
$xs["email-fields-revealed?"] = ($n1 or !empty($wa) and !empty($ua));
$xs["logged-in?"] = $pa;
$xs["logged-in-gip"] = $c1;
$xs["logout-url"] = $pa
? eq("e2m_gip_sign_out", ["provider" => E2GIP::get_logout_key()])
: "";
return $xs;
}
function sb($note_id)
{
return qb($note_id, "`IsNew` = 1");
}
function ab($note_id)
{
return qb($note_id, "`IsVisible` = 1");
}
function qb($note_id, $m1)
{
global $_config;
if (!is_numeric($note_id)) {
return 0;
}
$f1 = 0;
sm(
"SELECT count(*) " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
$note_id .
" " .
"AND (" .
$m1 .
")",
"count comments"
);
$h3 = qm();
$h3 = (int) $h3[0]["count(*)"];
$f1 = $h3;
return (int) $f1;
}
function lb(AeDatabaseConfiguration $databaseConfiguration)
{
if (Log::$a) {
__log("Count new comments");
}
$d1 = 0;
$s1 = "";
sm(
"SELECT `NoteID`, `Text` FROM `" .
$databaseConfiguration->getPrefix() .
"Comments` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `IsNew`=1 ORDER BY `Stamp` DESC",
"count new comments for author menu"
);
$h3 = qm();
$d1 = count($h3);
while ($d1-- > 0) {
if ($zy = wm($h3[$d1]["NoteID"])) {
$s1 = eq("e2m_note", ["*note" => $zy]);
break;
}
}
$d1++;
return [(int) $d1, $s1];
}
function zb($note_id)
{
global $_config;
if (Log::$a) {
__log("Comments: getting comments for note " . $note_id);
}
sm(
"SELECT c.*, g.`AuthorProfileLink` " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` c " .
"LEFT JOIN `" .
$_config["db_table_prefix"] .
"GIPsSessions` g " .
"ON c.`SubsetID`=g.`SubsetID` " .
"AND c.`GIP`=g.`GIP` " .
"AND c.`GIPAuthorID`=g.`GIPAuthorID` " .
"WHERE c.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
@$note_id .
" " .
"ORDER BY `Stamp`",
"get comments including deleted"
);
$h3 = qm();
return $h3;
}
function kb($zy, $a1 = "")
{
global $_config;
$pf = "ORDER BY `ID` DESC";
$vb = $q1 = [];
sm(
"SELECT DISTINCT `ID`, `Text`, `IsSubscriber`, `IsVisible`, " .
"`AuthorName`, `AuthorEmail`, `Stamp` " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
@$zy["ID"] .
" " .
"AND `IsSubscriber`=1 " .
"AND `IsVisible`=1 " .
"AND `AuthorEmail`!='" .
lm($a1) .
"' " .
$pf,
"get subscribers by note"
);
$h3 = qm();
foreach ($h3 as $qa) {
if (!in_array($qa["AuthorEmail"], $q1)) {
$vb[] = $qa;
}
$q1[] = $qa["AuthorEmail"];
}
return $vb;
}
function xb($zy, $l1 = NOTE_COMMENTABLE_NOW)
{
global $settings, $_config;
$z1 = true;
if (@$settings["comments"]["fresh_only"]) {
if (isset($_config["comment_freshness_days"])) {
if (
$zy["Stamp"] <
time() - $_config["comment_freshness_days"] * SECONDS_IN_A_DAY
) {
$z1 = false;
}
}
}
$k1 = $zy["IsCommentable"];
if ($l1 == NOTE_COMMENTABLE_NOW_CONDITIONALLY) {
$k1 = true;
}
return ff($zy) === "public" and $z1 and $k1;
}
function e2_commentrec_with_parameters_($parameters = [])
{
$zy = $parameters["*note"];
$x1 = zb($zy["ID"]);
$ls = @$x1[$parameters["comment-number"] - 1];
if ($ls) {
$ls["noterec"] = $zy;
return $ls;
}
}
function rb()
{
global $settings, $_config;
if (Log::$a) {
__log("Process comment form");
}
od();
$bn = a();
$note_id = $qs = $name = $js = $e1 = "";
if (array_key_exists("note-id", $_POST)) {
$note_id = trim(@$_POST["note-id"]);
}
if (array_key_exists("comment-id", $_POST)) {
$qs = trim(@$_POST["comment-id"]);
}
if (array_key_exists("comment-number", $_POST)) {
$ka = trim(@$_POST["comment-number"]);
}
if (array_key_exists("name", $_POST)) {
$name = trim(@$_POST["name"]);
}
if (array_key_exists($bn, $_POST)) {
$js = trim(@$_POST[$bn]);
}
if (array_key_exists("text", $_POST)) {
$e1 = trim(@$_POST["text"]);
}
if ($qs === "new") {
$r1 = hy();
if ($r1) {
$y1 = wy($r1);
$name = trim($y1["AuthorName"]);
$js = "";
$t1 = $y1["GIPAuthorID"];
}
} else {
if (array_key_exists("gip", $_POST)) {
$r1 = trim(@$_POST["gip"]);
}
}
$j1 =
(array_key_exists("already-subscribed", $_POST) and
$_POST["already-subscribed"] or
array_key_exists("subscribe", $_POST) and $_POST["subscribe"]);
$in = time();
if (!is_numeric($note_id)) {
throw new AeFormInconsistentException();
}
if (!is_numeric($qs) and $qs !== "new") {
throw new AeFormInconsistentException();
}
if ($qs !== "new" and !ys()) {
throw new AeFormInconsistentException();
}
if ($e1 == "" or !$r1 and ((string) $name === "" or (string) $js === "")) {
throw new AeFormIncompleteException($note_id);
}
if ($qs == "new" and !$r1) {
e1("commenter_name", $name);
e1("commenter_email", $js);
}
$h1 =
($qs === "new" and
(x() or e2_cookie_data_is_spam_suspicios_for_note_id_($note_id)));
if ($qs == "new") {
$g1 = @unserialize(file_get_contents(USER_DIR . "/last-comment.psa"));
if (md5($name . $js . $e1) == @$g1["md5"]) {
throw new AeFormDuplicateCommentException($e1);
}
if (
isset($_config["max_comment_length"]) and
strlen(@$_POST["text"]) > $_config["max_comment_length"]
) {
throw new AeFormCommentTooLongException($e1);
}
$zy = wm($note_id);
if ($qs == "new" and !xb($zy)) {
throw new AeFormNoteNotCommentableException($e1);
}
if ($h1) {
throw new AeFormCommentIsSpamSuspectException($e1);
}
}
e2_drop_caches_for_note_($note_id, true);
if ($qs == "new") {
$ls = [
"NoteID" => (int) $note_id,
"AuthorName" => $name,
"AuthorEmail" => $js,
"Text" => $e1,
"Reply" => "",
"IsVisible" => 1,
"IsAnswerAware" => 1,
"IsSubscriber" => (int) $j1,
"IsSpamSuspect" => (int) $h1,
"IsNew" => 1,
"Stamp" => (int) time(),
"LastModified" => (int) time(),
"IP" => lm(pd()),
"IsGIPUsed" => intval(!empty($r1) && !empty($t1)),
"GIP" => !empty($r1) ? lm($r1) : "",
"GIPAuthorID" => !empty($t1) ? lm($t1) : "",
];
$ls = mm(bl(), "Comments", $ls);
$qs = $ls["ID"];
$g1 = ["id" => $qs, "md5" => md5($name . $js . $e1)];
@e3(USER_DIR . "last-comment.psa", serialize($g1));
$w1 = md5($ls["ID"] . $ls["Stamp"] . "x");
e1("commenter_ph", $w1);
$zy = wm($note_id);
$na = eq("e2m_note", ["*note" => $zy]);
$ma["comment-time"] = [$in, pa()];
$ma["commenter"] = $name;
$ma["commenter-email"] = $js;
$ma["comment-text"] = $e1;
$ma["note-title"] = $zy["Title"];
$ma["note-href"] = $na;
$ma["comment-href"] = $na;
$ma["comments-disable-href"] = eq("e2s_note_flag", [
"*note" => $zy,
"flag" => "IsCommentable",
"value" => 0,
]);
$ma["reply-href"] = eq("e2m_comment_reply", [
"*note" => $zy,
"comment-number" => $ka,
]);
if (
isset($settings["author_email"]) and
@$settings["notifications"]["new_comments"]
) {
$fa = kn("comment-new-to-author", $ma);
$da = e2l_get_string("em--comment-new-to-author-subject", $ma);
$sa = $settings["author_email"];
$aa =
"From: " .
xn() .
"\r\n" .
"Reply-to: " .
$name .
" <" .
$js .
">";
en($sa, $da, $fa, $aa);
}
if (!$h1) {
unset($ma["commenter-email"]);
$aa = "From: " . xn();
foreach (kb($zy, $js) as $qa) {
$la = $qa["AuthorEmail"];
$za = md5($qa["ID"] . $qa["Stamp"] . "x");
$ma["unsubscribe-href"] = eq("e2m_unsubscribe", [
"*note" => $zy,
"unsubscribe-email" => $la,
"unsubscribe-key" => $za,
]);
$sa = $la;
$fa = kn("comment-new-to-public", $ma);
$da = e2l_get_string("em--comment-new-to-public-subject", $ma);
en($sa, $da, $fa, $aa);
}
}
} else {
$u1 = [
"ID" => $qs,
"Text" => $e1,
"IsVisible" => 1,
"IsSubscriber" => ((int) $j1),
"LastModified" => time(),
];
if (!empty($name)) {
$u1["AuthorName"] = $name;
}
if (!empty($js)) {
$u1["AuthorEmail"] = $js;
}
fm(bl(), "Comments", $u1);
}
return (int) $note_id;
}
define(
"E2_UA_STRING",
"Aegea " .
E2_RELEASE .
" (v" .
E2_VERSION .
(defined("E2_EDITION") ? "e" : "") .
")"
);
define("E2_MINIMUM_PHP", "5.6");
define("E2_MINIMUM_MYSQL", "5.6");
define("E2_MINIMUM_MARIADB", "10.1");
define("E2E_STRANGE_ERROR", 10);
define("E2E_USER_ERROR", 20);
define("E2E_PERMISSIONS_ERROR", 30);
define("E2E_MESSAGE", 100);
define("E2E_DIAGNOSTICS_MESSAGE", 110);
define("DEFAULT_TEMPLATE", "acute");
define("DEFAULT_FORMATTER", "neasden");
define("E2_NEW_FILES_RIGHTS", 0777);
define("E2_JSON_STYLE", JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
define("DEFAULT_ITEMS_PER_PAGE", 10);
define("MAX_ITEMS_PER_PAGE", 100);
define("SYSTEM_DIR", "system/");
define("SYSTEM_DEFAULTS_DIR", "system/default/");
define("SYSTEM_THEME_DIR", "system/theme/");
define("LANGUAGES_DIRNAME", "languages/");
define("LIBRARY_DIRNAME", "library/");
define("THEMES_DIRNAME", "themes/");
define("EXTRAS_DIRNAME", "extras/");
define("SCRIPTS_SUBDIR", "js/");
define("LOGS_DIRNAME", "logs/");
define("CACHES_DIRNAME", "caches/");
define("BACKUP_DIRNAME", "backup/");
define("MAIN_LOG_FILENAME", "main.log");
define("PICTURES_DIRNAME", "pictures/");
define("THUMBNAILS_DIRNAME", "pictures/thumbs/");
define("AVATARS_DIRNAME", "pictures/avatars/");
define("USERPIC_DIRNAME", "pictures/userpic/");
define("VIDEO_DIRNAME", "video/");
define("AUDIO_DIRNAME", "audio/");
define("LICENSE_FILENAME", "license.psa");
define("THUMB_WIDTH", 180);
define("THUMB_HEIGHT", 120);
define("THUMB_JPG_QUALITY", 50);
define("SCALED_IMAGE_JPG_QUALITY", 80);
define("AVATAR_SIZE", 80);
define("VIDEO_ICON_FILENAME", "images/video.svg");
define("AUDIO_ICON_FILENAME", "images/audio.svg");
define("VIDEO_ICON_WIDTH", 180);
define("VIDEO_ICON_HEIGHT", 120);
define("AUDIO_ICON_WIDTH", 120);
define("AUDIO_ICON_HEIGHT", 120);
define("ALIAS_MAX_LENGTH", 64);
define("CACHE_ALIASMAP", CACHE and true);
define("CACHE_NOTES", CACHE and true);
define("CACHE_NOTES_RELATED", CACHE and true);
define("CACHE_NOTES_COMMENTS", CACHE and true);
define("CACHE_POPULAR", CACHE and true);
define("CACHE_POPULAR_WITH_TAG", CACHE and true);
define("CACHE_RANDOM_NOTE", CACHE and true);
define("CACHE_TAGS", CACHE and true);
define("CACHE_FAVTAGS", CACHE and true);
define("CACHE_NOTES_COUNTS", CACHE and true);
define("CACHE_EDGE_TIMEINFO", CACHE and true);
define("CACHE_FRONTPAGE", CACHE and true);
define("CACHE_FRONTPAGE_FEED", CACHE and true);
define("CACHE_TAG", CACHE and true);
define("CACHE_FULLLIST", CACHE and true);
define("CACHE_DRAFTS", CACHE and true);
define("CACHE_DRAFTS_ALIAS_USE_COUNTS", CACHE and true);
define("CACHE_LASTMODIFIEDS", CACHE and true);
define("CACHE_INDEXED_FLAG", CACHE and true);
define("CACHE_FILENAME_ALIASMAP", CACHES_DIRNAME . "aliasmap.psa");
define("CACHE_FILENAMES_NOTES", CACHES_DIRNAME . "note-*.psa");
define("CACHE_FILENAMES_NOTES_RELATED", CACHES_DIRNAME . "note-*-related.psa");
define(
"CACHE_FILENAMES_NOTES_COMMENTS",
CACHES_DIRNAME . "note-*-comments.ctree.psa"
);
define(
"CACHE_FILENAMES_NOTES_COMMENTS_AUTHOR",
CACHES_DIRNAME . "note-*-comments-author.ctree.psa"
);
define("CACHE_FILENAMES_NOTES_COUNTS", CACHES_DIRNAME . "notes-count-*.txt");
define("CACHE_FILENAMES_EDGE_TIMEINFO", CACHES_DIRNAME . "*.e2time.psa");
define("CACHE_FILENAME_POPULAR", CACHES_DIRNAME . "popular.ctree.psa");
define(
"CACHE_FILENAME_POPULAR_EXPIRES",
CACHES_DIRNAME . "popular-expires.txt"
);
define("CACHE_FILENAME_RANDOM_NOTE", CACHES_DIRNAME . "random-note.psa");
define(
"CACHE_FILENAMES_POPULAR_WITH_TAG",
CACHES_DIRNAME . "popular-*.ctree.psa"
);
define(
"CACHE_FILENAMES_POPULAR_WITH_TAG_EXPIRES",
CACHES_DIRNAME . "popular-*-expires.txt"
);
define("CACHE_FILENAME_TAGS", CACHES_DIRNAME . "tags.ctree.psa");
define("CACHE_FILENAME_TAGS_FULL", CACHES_DIRNAME . "tags-full.ctree.psa");
define("CACHE_FILENAME_TAGS_AUTHOR", CACHES_DIRNAME . "tags-author.ctree.psa");
define(
"CACHE_FILENAME_TAGS_AUTHOR_FULL",
CACHES_DIRNAME . "tags-author-full.ctree.psa"
);
define("CACHE_FILENAME_FAVTAGS", CACHES_DIRNAME . "favtags.ctree.psa");
define("CACHE_FILENAME_FRONTPAGE", CACHES_DIRNAME . "frontpage.ctree.psa");
define(
"CACHE_FILENAME_FRONTPAGE_AUTHOR",
CACHES_DIRNAME . "frontpage-author.ctree.psa"
);
define("CACHE_FILENAME_FRONTPAGE_FEED", CACHES_DIRNAME . "frontpage-feed.psa");
define("CACHE_FILENAMES_TAG", CACHES_DIRNAME . "tag-*.ctree.psa");
define("CACHE_FILENAMES_TAG_AUTHOR", CACHES_DIRNAME . "tag-*-author.ctree.psa");
define("CACHE_FILENAME_FULLLIST", CACHES_DIRNAME . "notes-list.ctree.psa");
define("CACHE_FILENAME_DRAFTS", CACHES_DIRNAME . "drafts.psa");
define(
"CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS",
CACHES_DIRNAME . "drafts-auc.psa"
);
define(
"CACHE_FILENAME_LASTMODIFIEDS",
CACHES_DIRNAME . "last-modifieds-by-id.psa"
);
define("CACHE_FILENAME_INDEXED_FLAG", CACHES_DIRNAME . "indexed.flag");
define("FP_NO_ID_OR_NEW", -1);
define("FP_INSERT_ERROR", -10);
define("FP_UPDATE_ERROR", -11);
define("FP_EMPTY_FIELD", -20);
define("FP_TITLE_OR_TEXT_EMPTY", -21);
define("FP_NOT_COMMENTABLE", -30);
define("FP_COMMENT_DOUBLE_POST", -101);
define("FP_COMMENT_TOO_LONG", -102);
define("FP_COMMENT_SPAM_SUSPECT", -103);
define("NOTE_COMMENTABLE_NOW", -1);
define("NOTE_COMMENTABLE_NOW_CONDITIONALLY", -2);
define("SECONDS_IN_A_MINUTE", 60);
define("SECONDS_IN_AN_HOUR", 3600);
define("SECONDS_IN_A_DAY", 86400);
define("SECONDS_IN_A_WEEK", 604800);
define("SECONDS_IN_A_MONTH", 2592000);
define("SECONDS_IN_A_YEAR", 31536000);
function e2m_drafts($parameters)
{
global $_strings, $_config;
$draftsView = new AePageableNotesView("e2m_drafts", $parameters);
$draftsView->setPortionSize((int) $_config["drafts_per_page"]);
$draftsView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$draftsView->setWantControls(true);
$draftsView->setWantPaging(true);
$draftsView->setUseLocalHrefs(true);
if ($draftsView->isFirstPage() and CACHE_DRAFTS) {
$draftsView->setCacheFilename(USER_DIR . CACHE_FILENAME_DRAFTS);
}
$draftsView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=0 " .
"ORDER BY `LastModified` DESC"
);
$i1 = $draftsView->getNotesCTree();
if (count($i1)) {
if (Log::$a) {
__log("Thumbnails {");
}
foreach ($i1 as $k3 => $x3) {
$i1[$k3]["thumbs"] = e2_(@$x3["format-info"]["resources-detected"]);
}
if (Log::$a) {
__log("}");
}
}
$ss = $_strings["pt--drafts"];
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => $_strings["pt--drafts"],
"notes" => $i1,
"pages" => $draftsView->getPagesCTree(),
];
if (count($i1) >= 5) {
$vb["secret-link-promo"] = e2l_get_string("pm--secret-link", [
"url" => $_config["paid_features_url"],
]);
}
if ($draftsView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-drafts"];
} elseif (!$draftsView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function tb($o1)
{
global $_config;
if (Log::$a) {
__log("Drafts: find duplicate OriginalAliases...");
}
if (
CACHE_DRAFTS_ALIAS_USE_COUNTS and
is_file(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS)
) {
$p1 = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS)
);
}
if (CACHE_DRAFTS_ALIAS_USE_COUNTS and @is_array($p1)) {
if (Log::$a) {
__log("Drafts: retrieve cached");
}
} else {
if (Log::$a) {
__log("Drafts: assemle cacheable...");
}
$p1 = [];
sm(
"SELECT `OriginalAlias` FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=0 " .
"ORDER BY `ID`",
"get original aliases of drafts to calculate use counts"
);
$h3 = qm();
$tn = [];
foreach ($h3 as $k3 => $zy) {
@$p1[$zy["OriginalAlias"]]++;
}
if (CACHE_DRAFTS_ALIAS_USE_COUNTS) {
e3(
USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS,
serialize($p1)
);
}
}
return $p1[$o1];
}
function jb()
{
global $_strings;
$cq = "https://" . $_strings["e2--website-host"] . "/";
$vq =
"(" .
$_strings["e2--release"] .
" " .
E2_RELEASE .
", v" .
E2_VERSION .
")";
return [
"built?" => BUILT,
"installed?" => yn() !== null,
"version" => "v" . E2_VERSION,
"version-description" => $_strings["e2--vname-aegea"] . " " . $vq,
"user-folder-name" => iq(),
"cookie-prefix" => x1(),
"href" => $cq,
"about" =>
'<span title="E2 ' .
$vq .
'">' .
$_strings["e2--powered-by"] .
" " .
'<a href="' .
$cq .
'" class="nu"><u>' .
$_strings["e2--vname-aegea"] .
"</u>" .
'<span class="e2-svgi">' .
c2("aegea") .
"</span></a></span>",
];
}
function hb($bq, $type = E2E_STRANGE_ERROR)
{
global $errors, $_config;
if (!isset($errors)) {
$errors = [];
}
$yq = !ys() + 1 <= (int) $_config["show_call_stack"];
if ($bq) {
if ($bq[0] != "<") {
$bq = "<p>" . $bq . "</p>";
}
$nq = ["description" => $bq, "type" => $type];
if ($type == E2E_STRANGE_ERROR and $yq) {
$nq["backtrace"] = debug_backtrace();
}
$errors[] = $nq;
}
return true;
}
function gb($mq)
{
global $_strings;
if (count($mq) == 0) {
return false;
}
$fq = "";
$fq .=
"<p>" .
$_strings["gs--enable-write-permissions-for-the-following"] .
"</p>";
$fq .= "<ul>";
foreach ($mq as $jv) {
if ($jv == ".") {
$jv = "";
}
$fq .= "<li><tt>./" . $jv . "</tt></li>";
}
$fq .= "</ul>";
return $fq;
}
function wb($dq, $bq, $sq = false, $aq = false, $qq = [])
{
global $errors;
if (!(error_reporting() & $dq) or $dq & 8) {
return;
}
$sq = str_replace(__DIR__, "", $sq);
hb($sq . ", line " . $aq . "<br />Error " . $dq . ": " . $bq);
$errors[count($errors) - 1]["phpcode"] = $dq;
}
function ub($lq, $zq, $s2, $bf)
{
if (!(error_reporting() & $lq)) {
return;
}
throw new ErrorException($zq, 0, $lq, $s2, $bf);
}
function ib()
{
global $errors, $_config;
if (!isset($errors)) {
$errors = [];
}
@session_start();
if (is_array(@$_SESSION["errors"])) {
$e = array_merge(@$_SESSION["errors"], $errors);
} else {
$e = $errors;
}
$yq = !ys() + 1 <= (int) $_config["show_call_stack"];
if (@$_config["store_backtrace"] and $yq and $e != null) {
@e3("backtrace.psa", serialize($e));
} else {
@unlink("backtrace.psa");
}
if (isset($_SESSION["errors"])) {
unset($_SESSION["errors"]);
}
$vb = [];
$kq = false;
if (count($e) > 0) {
foreach ($e as $gb => $xq) {
if ($xq["type"] == E2E_STRANGE_ERROR) {
$xq["class"] = "serious";
$kq = true;
if ($yq) {
$xq["backtrace"] = pb($xq["backtrace"]);
}
}
if ($xq["type"] == E2E_MESSAGE) {
$xq["class"] = "info";
}
$e[$gb] = $xq;
}
$vb["each"] = $e;
if (
$kq and
@$_config["store_backtrace"] and
$yq and
is_file("debug.php")
) {
$vb["debug-link"] = "debug.php";
}
}
return $vb;
}
function ob()
{
$errors = ib();
foreach ($errors["each"] as $eq) {
echo "<p>" . $eq["description"] . "</p>";
}
die();
}
function pb($rq)
{
if (!is_array($rq)) {
return "No backtrace info";
}
$rq = array_reverse($rq);
$rq = array_splice($rq, 0, count($rq) - 1);
$e =
'<p style="background: #fea; padding: .25em .5em; line-height: 1em; overflow: hidden">';
foreach ($rq as $gb => $tq) {
($jq = @$tq["args"]) or ($jq = []);
$hq = [];
foreach ($jq as $gq) {
$hq[] = var_export($gq, true);
}
$s2 = @$tq["file"];
$s2 = str_replace($_SERVER["DOCUMENT_ROOT"], "", $s2);
$bf = @$tq["line"] ? " #" . $tq["line"] : "?";
$e .= '<div style="margin: .25em 0 .5em ' . $gb * 3 . 'em">';
$e .=
'<span style="float: right; color: #666"> ' . $s2 . $bf . "</span>";
$e .= "<tt><b>" . @$tq["function"] . " (</b>";
if (count($hq)) {
$wq = str_replace("array (\n)", "array ()", $hq);
$wq = implode(", ", $wq);
if (0) {
$wq = highlight_string("<?" . $wq . "?" . ">", true);
$wq = substr($wq, 77, -28);
}
$wq = str_replace(" ", " ", $wq);
$wq = nl2br($wq);
$e .= '<div style="margin: 0 0 0 1.12em">' . $wq . "</div>";
}
$e .= "<b>)</b> →</tt></div>";
}
$e .= "</p>";
return $e;
}
class AeException extends \Exception
{
}
class AeMySQLException extends AeException
{
}
class AeMySQLNotFoundException extends AeMySQLException
{
}
class AeMySQLTooOldException extends AeMySQLException
{
}
class AeMySQLCannotConnectException extends AeMySQLException
{
}
class AeMySQLAccessDeniedException extends AeMySQLCannotConnectException
{
}
class AeMySQLQueryException extends AeMySQLException
{
}
class AeMySQLNoDataException extends AeMySQLException
{
}
class AeMySQLNotMigrateableException extends AeMySQLException
{
}
class AeMySQLCorruptedUpdateRecordCallException extends AeMySQLException
{
}
class AeRecordNotFoundException extends AeException
{
}
class AeInstallException extends AeException
{
}
class AeInstallAlreadyInstalledException extends AeInstallException
{
}
class AeInstallDatabaseOccupiedException extends AeInstallException
{
}
class AeWritePermissionsException extends AeException
{
}
class AeNotSavedException extends AeWritePermissionsException
{
}
class AeTokenException extends AeException
{
}
class AeOlbaException extends AeException
{
}
class AeOlbaTemplateMissingException extends AeOlbaException
{
}
class AeStubException extends AeException
{
}
class AeFormException extends AeException
{
}
class AeFormInconsistentException extends AeFormException
{
}
class AeFormIncompleteException extends AeFormException
{
public $note_id = "";
function __construct($note_id)
{
$this->note_id = $note_id;
parent::__construct();
}
}
class AeFormCommentUnacceptableException extends AeFormException
{
public $comment_text = "";
function __construct($comment_text)
{
$this->comment_text = $comment_text;
parent::__construct();
}
}
class AeFormDuplicateCommentException extends AeFormCommentUnacceptableException
{
}
class AeFormCommentTooLongException extends AeFormCommentUnacceptableException
{
}
class AeFormNoteNotCommentableException extends
AeFormCommentUnacceptableException
{
}
class AeFormCommentIsSpamSuspectException extends
AeFormCommentUnacceptableException
{
}
function c3($uq, $iq = false)
{
$oq = substr(__DIR__, 0, strrpos(__DIR__, "/"));
$pq = "";
$cl = [];
foreach (array_reverse($uq->getTrace()) as $vl) {
$bl["where"] =
str_replace($oq . "/", "", $vl["file"]) . ":" . $vl["line"];
$yl = [];
foreach ($vl["args"] as $nl) {
$yl[] = htmlspecialchars(
str_replace("\n", "\n ", var_export($nl, true)),
ENT_NOQUOTES,
"UTF-8"
);
}
$ml = "";
if (count($yl)) {
$ml = "\n" . " " . implode(",\n ", $yl) . "\n";
}
$bl["call"] = $vl["function"] . " (" . $ml . ")";
$cl[] = $bl;
}
do {
if ((string) $uq->getMessage() !== "") {
$pq .= $uq->getMessage() . "\n";
}
$pq .= "\n";
$pq .=
get_class($uq) .
" in " .
str_replace($oq . "/", "", $uq->getFile()) .
":" .
$uq->getLine() .
"\n";
if ($uq->getCode()) {
$pq .= "Code: " . $uq->getCode() . "\n";
}
$fl = "";
$gb = 1;
foreach ($cl as $bf) {
$fl .= $gb++ . ". " . $bf["where"] . " " . $bf["call"] . "\n";
if (!$iq) {
$fl .= "\n";
}
}
$pq .= "\n";
} while ($uq = $uq->getPrevious());
if ($iq) {
$fl = preg_replace('/^.*?$/smu', ' $0', $fl);
$pq .= "" . "\n";
$pq .= $fl;
$pq .= "";
} else {
$pq .= $fl;
}
return $pq;
}
function v3($uq, $zq = "")
{
global $_config;
if ($_config["dev_verbose"] > (int) !ys()) {
hb("<pre>" . c3($uq) . "</pre>");
}
if ($_config["log_errors"]) {
Log::$a = true;
if (Log::$a) {
qn('error-$');
}
}
if (Log::$a) {
__log("Exception caught: " . c3($uq, true));
}
if (Log::$a) {
qn("");
}
if ((string) $zq !== "") {
if (Log::$a) {
__log($zq);
}
}
}
function b3($uq)
{
global $_config, $content;
$content["title"] = ":-(";
$content["exception-message"] = $uq->getMessage();
$dl["error"]["message"] = ":-(";
if ($_config["dev_verbose"] > (int) !ys()) {
$content["exception-string"] = c3($uq);
$dl["error"]["message"] = nl2br(c3($uq));
}
if ($_config["log_errors"]) {
Log::$a = true;
if (Log::$a) {
qn('error-$');
}
}
if (Log::$a) {
__log("Panic: " . c3($uq, true));
}
if (Log::$a) {
__log(":-(");
}
if (
array_key_exists("result", $_POST) and
$_POST["result"] == "ajaxresult"
) {
$vb = json_encode($dl);
} else {
$vb = hf("panic", true);
}
echo $vb;
die();
}
function y3($uq)
{
b3($uq);
}
function e2m_most_commented($parameters = [])
{
global $settings, $_strings, $_config;
$gn = ys();
$mostCommentedView = new AePageableNotesView(
"e2m_most_commented",
$parameters
);
$mostCommentedView->setPortionSize(
$settings["appearance"]["notes_per_page"]
);
$mostCommentedView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$mostCommentedView->setWantNewCommentsCount($gn);
$mostCommentedView->setWantReadHrefs($_config["count_reads"]);
$mostCommentedView->setWantControls($gn and !@$_config["read_only"]);
$mostCommentedView->setWantHiddenTags($gn);
AeMainMenuManager::$isMostCommentedCurrent = $mostCommentedView->isFirstPage();
AeMainMenuManager::$isMostCommentedParent = !$mostCommentedView->isFirstPage();
$sl = $_config["hot_period"];
$al = time() - n3($_config["hot_period"]);
$mostCommentedView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
df($gn) .
"AND `ID` IN ( " .
"SELECT `NoteID` FROM ( " .
"SELECT `NoteID`, COUNT(*) `CommentsCount` " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsVisible` = 1 " .
"AND `Stamp` > " .
$al .
" " .
"GROUP BY `NoteID` " .
"ORDER BY `CommentsCount` DESC " .
") As MostCommentedNotesIDs " .
")"
);
$vb = [
"title" => e2l_get_string("pt--most-commented", ["period" => $sl]),
"heading" => e2l_get_string("pt--most-commented", ["period" => $sl]),
"notes" => $mostCommentedView->getNotesCTree(),
"pages" => $mostCommentedView->getPagesCTree(),
];
if ($mostCommentedView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-such-notes"];
} elseif (!$mostCommentedView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function e2m_favourites($parameters = [])
{
global $settings, $_config, $_strings;
$gn = ys();
$favouritesView = new AePageableNotesView("e2m_favourites", $parameters);
$favouritesView->setPortionSize($settings["appearance"]["notes_per_page"]);
$favouritesView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$favouritesView->setWantPaging(true);
$favouritesView->setWantNewCommentsCount($gn);
$favouritesView->setWantReadHrefs($_config["count_reads"]);
$favouritesView->setWantControls($gn and !@$_config["read_only"]);
$favouritesView->setWantHiddenTags($gn);
AeMainMenuManager::$isFavouritesCurrent = $favouritesView->isFirstPage();
AeMainMenuManager::$isFavouritesParent = !$favouritesView->isFirstPage();
$favouritesView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `IsFavourite`=1 " .
df($gn) .
"ORDER BY `Stamp` DESC"
);
$ss = $_strings["pt--favourites"];
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => $_strings["pt--favourites"],
"notes" => $favouritesView->getNotesCTree(),
"pages" => $favouritesView->getPagesCTree(),
];
if ($favouritesView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-favourites"];
} elseif (!$favouritesView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function n3($sl)
{
if ("year" == $sl) {
return SECONDS_IN_A_YEAR;
} elseif ("month" == $sl) {
return SECONDS_IN_A_MONTH;
} elseif ("week" == $sl) {
return SECONDS_IN_A_DAY * 7;
} elseif ("day" == $sl) {
return SECONDS_IN_A_DAY;
} else {
return PHP_INT_MAX;
}
}
function e2m_json($parameters = [])
{
list($ql, $in) = q3();
$ll = json_encode($ql, E2_JSON_STYLE);
x3($ll, $in, "json");
}
function e2m_rss($parameters = [])
{
list($ql, $in) = q3();
$zl = e2feeds__rss_using_jsonfeed_array_($ql);
x3($zl, $in, "rss");
}
function e2m_tag_json($parameters = [])
{
if (array_key_exists("*tag", $parameters)) {
$wb = $parameters["*tag"];
} else {
return e2m_error404();
}
list($ql, $in) = l3($wb);
$ll = json_encode($ql, E2_JSON_STYLE);
x3($ll, $in, "json");
}
function e2m_tag_rss($parameters = [])
{
if (array_key_exists("*tag", $parameters)) {
$wb = $parameters["*tag"];
} else {
return e2m_error404();
}
list($ql, $in) = l3($wb);
$zl = e2feeds__rss_using_jsonfeed_array_($ql);
x3($zl, $in, "rss");
}
function e2m_note_json($parameters = [])
{
global $settings, $_current_url;
$zy = $parameters["*note"];
if ($zy == false) {
return e2m_error404();
}
$gn = ys();
if (!(ff($zy) === "public" or $gn and $zy["IsPublished"])) {
return e2m_error404();
}
$in = $zy["Stamp"];
$kl = e2_jsonfeed_item_array_from_noterec_($zy);
$xl = [$kl];
$ql = e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl);
$ql["title"] = ev();
$ql["_rss_description"] = a3();
$ql["home_page_url"] = eq("e2m_frontpage", ["page" => 1]);
$ql["feed_url"] = $_current_url;
x3(json_encode($ql, E2_JSON_STYLE), $in, "json");
}
function e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl)
{
global $_lang, $_config, $settings;
$vb = [
"version" => "https://jsonfeed.org/version/1.1",
"title" => null,
"_rss_description" => null,
"_rss_language" => $_lang,
"_itunes_email" => "",
"_itunes_categories_xml" => "",
"_itunes_image" => "",
"_itunes_explicit" => "",
"home_page_url" => null,
"feed_url" => null,
"icon" => tv(),
"authors" => [
[
"name" => rv(),
"url" => eq("e2m_frontpage", ["page" => 1]),
"avatar" => tv(),
],
],
"items" => $xl,
"_e2_version" => E2_VERSION,
"_e2_ua_string" => E2_UA_STRING,
];
return $vb;
}
function e2_jsonfeed_item_array_from_noterec_($zy)
{
$url = eq("e2m_note", ["*note" => $zy]);
$el = n1("Y-m-d\TH:i:s", $zy["Stamp"]) . q1($zy["Stamp"], ":");
$rl =
n1("Y-m-d\TH:i:s", $zy["LastModified"]) . q1($zy["LastModified"], ":");
$tl = n1("D, d M Y H:i:s ", $zy["Stamp"]) . q1($zy["Stamp"]);
$ld = ly($zy["FormatterID"], @$zy["Text"], "full-rss");
$noteView = new AeNoteView($zy);
$u3 = $noteView->getNoteCTree();
$m3 = $u3["og-images"];
$jl = [];
foreach ($u3["tags"] as $gv) {
$jl[] = $gv["name"];
}
$v = [
"id" => (string) $zy["ID"],
"url" => $url,
"title" => ay($zy["Title"]),
"content_html" => $ld["text-final"],
"date_published" => $el,
"date_modified" => $rl,
"tags" => $jl,
];
if ($zy["IsExternal"]) {
$hl = bn($zy);
$v["url"] = $hl["href-external"];
$v["author"] = [
"name" => $hl["author"],
"url" => $hl["author-href"],
"avatar" => $hl["userpic-href"],
];
}
if (count($m3) > 0) {
$v["image"] = $m3[0];
}
$v["_date_published_rfc2822"] = $tl;
$v["_rss_guid_is_permalink"] = "false";
$v["_rss_guid"] = (string) $zy["ID"];
$v["_e2_data"] = [
"is_favourite" => (bool) $zy["IsFavourite"],
"links_required" => $ld["meta"]["links-required"],
"og_images" => $m3,
];
return $v;
}
function d3($gl, $ss, $s1)
{
global $_newsfeeds;
if (!isset($_newsfeeds)) {
$_newsfeeds = [];
}
$wl = "";
if ($gl == "rss") {
$wl = "application/rss+xml";
}
if ($gl == "json") {
$wl = "application/json";
}
$_newsfeeds[] = [
"type" => $wl,
"title" => htmlspecialchars($ss, ENT_NOQUOTES, "UTF-8"),
"href" => $s1,
];
}
function s3()
{
global $_config;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
df() .
"ORDER BY `Stamp` DESC " .
"LIMIT " .
$_config["rss_items"],
"get recent public noterecs for RSS or JSONFeed"
);
return qm();
}
function a3()
{
global $settings;
if (!empty($settings["meta_description"])) {
$ul = strip_tags(
ay(
htmlspecialchars(
$settings["meta_description"],
ENT_NOQUOTES,
"UTF-8"
)
)
);
} elseif (!empty($settings["blog_subtitle"])) {
$ld = zy($settings["blog_subtitle"], "full");
$ul = $ld["text-final"];
$ul = mf($ul);
} else {
$ul = ev();
}
return $ul;
}
function q3()
{
global $settings, $_current_url;
$in = 0;
$xl = [];
$ql = [];
$of = USER_DIR . CACHE_FILENAME_FRONTPAGE_FEED;
if (CACHE_FRONTPAGE_FEED and is_file($of)) {
if (Log::$a) {
__log("Feed array (RSS, JSON): cached");
}
$ql = @unserialize(file_get_contents($of));
$in = filemtime($of);
} else {
if (Log::$a) {
__log("Feed array (RSS, JSON): not cached, will need to build");
}
$ff = s3();
foreach ($ff as $zy) {
$xl[] = e2_jsonfeed_item_array_from_noterec_($zy);
$in = max($in, $zy["Stamp"]);
}
$ql = e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl);
$ql["title"] = ev();
$ql["_rss_description"] = a3();
$ql["home_page_url"] = eq("e2m_frontpage", ["page" => 1]);
$ql["feed_url"] = $_current_url;
if (CACHE_FRONTPAGE_FEED) {
e3($of, serialize($ql));
}
}
return [$ql, $in];
}
function l3($wb)
{
global $_config, $_strings, $_current_url;
$in = 0;
$xl = [];
sm(
"SELECT n.* " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"INNER JOIN `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk " .
"ON nk.`NoteID` = n.`ID` " .
"WHERE n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (nk.`KeywordID` = " .
$wb["ID"] .
") " .
"AND n.`IsPublished` = 1 " .
df(ys()) .
"ORDER BY n.`Stamp` DESC " .
"LIMIT " .
$_config["rss_items"],
"get tag noterecs for RSS or JSONFeed"
);
$ff = qm();
foreach ($ff as $zy) {
$xl[] = e2_jsonfeed_item_array_from_noterec_($zy);
$in = max($in, $zy["Stamp"]);
}
if ((string) $wb["Summary"] !== "") {
$ul = strip_tags(
ay(htmlspecialchars($wb["Summary"], ENT_NOQUOTES, "UTF-8"))
);
} elseif ((string) $wb["Description"] !== "") {
$ld = zy($wb["Description"], "full");
$ul = $ld["text-final"];
$ul = mf($ul);
} else {
$ul = a3();
}
$il = htmlspecialchars($wb["PageTitle"], ENT_COMPAT, "UTF-8");
if ((string) $il !== "") {
$ss = $il;
} else {
$ss =
ev() .
": " .
$_strings["gs--posts-tagged"] .
" " .
htmlspecialchars($wb["Keyword"], ENT_COMPAT, "UTF-8");
}
$ql = e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl);
$ql["title"] = $ss;
$ql["_rss_description"] = $ul;
$ql["home_page_url"] = eq("e2m_tag", ["*tag" => $wb]);
$ql["feed_url"] = $_current_url;
return [$ql, $in];
}
function e2feeds__rss_using_jsonfeed_array_($content)
{
$ol = USER_DIR . "rss/rss.tmpl.php";
if (!is_file($ol)) {
$ol = SYSTEM_DEFAULTS_DIR . "rss/rss.tmpl.php";
}
if (is_file($ol)) {
ob_start();
include $ol;
$zl = ob_get_contents();
ob_end_clean();
}
return $zl;
}
function k3($zl)
{
$pl = "";
for ($gb = 0; $gb < strlen($zl); ++$gb) {
if (in_array(ord($zl[$gb]), [10, 13]) or ord($zl[$gb]) >= 32) {
$pl .= $zl[$gb];
}
}
return $pl;
}
function x3($c4, $in, $gl)
{
global $_config;
$v4 = gmdate("r", $in);
$b4 = md5($in);
if ($gl == "rss") {
if (@$_config["dev_xml_as_text"]) {
header("Content-Type: text/plain");
} else {
header("Content-Type: application/xml; charset=utf-8");
}
} elseif ($gl == "json") {
header("Content-Type: application/json");
} else {
header("Content-Type: text/plain");
}
header("Last-modified: " . $v4);
header("Etag: " . $b4);
header("Cache-Control: public");
header("Expires: " . date("r", $in + SECONDS_IN_A_DAY));
$y4 = isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])
? stripslashes($_SERVER["HTTP_IF_MODIFIED_SINCE"])
: false;
$n4 = isset($_SERVER["HTTP_IF_NONE_MATCH"])
? stripslashes($_SERVER["HTTP_IF_NONE_MATCH"])
: false;
if (!$y4 && !$n4 or $n4 && $n4 != $b4 or $y4 && $y4 != $v4) {
if ($gl == "rss") {
$c4 = k3($c4);
}
ini_set("zlib.output_compression", 0);
echo $c4;
ini_set("zlib.output_compression", 1);
} else {
header("HTTP/1.1 304 Not Modified");
}
die();
}
define("CROP_NONE", 0);
define("CROP_SQUARE", 1);
function e3($s2, $m4)
{
@nq(dirname($s2));
if (!@file_put_contents($s2, $m4, LOCK_EX)) {
return false;
}
@chmod($s2, E2_NEW_FILES_RIGHTS);
return true;
}
function e2s_retrieve($parameters)
{
$url = base64_decode(strtr($parameters["url"], "-_", "+/"));
if (Log::$a) {
__log("Retrieve: " . $url);
}
h2($url, PROVIDE_MEDIA_NOW);
die();
}
function r3($uy, $f4, $v3)
{
$d4 = [];
if (is_array($v3)) {
$d4 = l2($v3);
}
($s4 = @unserialize($f4["Uploads"])) or ($s4 = []);
$a4 = array_diff($d4, $s4);
if (count($a4) > 0) {
u3($uy, $f4["ID"], "add", $a4);
}
return $a4;
}
function t3($q4)
{
$tv = [];
foreach (x2($q4) as $l4) {
$tv[] = $l4["src"];
}
return $tv;
}
function j3($name, $z4)
{
$name = t1($name);
if (preg_match("//u", $name)) {
$name = nl($name, false);
}
$k4 = "";
for ($gb = 0; $gb < strlen($name); $gb++) {
if ($name[$gb] == "?") {
$k4 .= "";
} elseif ($name[$gb] == " ") {
$k4 .= "-";
} elseif (ord($name[$gb]) <= 127) {
$k4 .= $name[$gb];
}
}
if ($k4 == "") {
$k4 = $z4;
}
if ($k4[0] == ".") {
$k4 = $z4 . $k4;
}
return $k4;
}
function h3($x4)
{
global $_config;
if (Log::$a) {
__log("Count references for upload <" . $x4 . ">");
}
if (is_file(USER_DIR . "new-uploads.psa")) {
$e4 = @unserialize(file_get_contents(USER_DIR . "new-uploads.psa"));
}
$r4 = "%" . str_replace("%", "#%", $x4) . "%";
sm(
"SELECT `ID`, `Text`, `FormatterID`, `Uploads` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (`Text` LIKE '" .
$r4 .
"' ESCAPE '#' " .
"OR `Uploads` LIKE '" .
$r4 .
"' ESCAPE '#')",
"get notes where uploads may be referenced"
);
$h3 = qm();
$t4 = @unserialize($h3[0]["Uploads"]);
if (!is_array($t4)) {
foreach ($h3 as $zy) {
$ld = ly($zy["FormatterID"], @$zy["Text"], "full-rss");
$t4 = r3("note", $zy, $ld["meta"]["resources-detected"]);
}
}
sm(
"SELECT `ID`, `Description`, `Uploads` " .
"FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (`Description` LIKE '" .
$r4 .
"' ESCAPE '#' " .
"OR `Uploads` LIKE '" .
$r4 .
"' ESCAPE '#')",
"get tags where uploads may be referenced"
);
$h3 = qm();
$j4 = @unserialize($h3[0]["Uploads"]);
if (!is_array($j4)) {
foreach ($h3 as $wb) {
$ld = zy(@$wb["Description"], "full-rss");
$j4 = r3("tag", $wb, $ld["meta"]["resources-detected"]);
}
}
if (!is_array($e4)) {
$e4 = [];
}
if (!is_array($t4)) {
$t4 = [];
}
if (!is_array($j4)) {
$j4 = [];
}
$h4 = array_merge($e4, $t4, $j4);
if (Log::$a) {
__log("References found in relevant entries: " . var_export($h4, true));
}
if (in_array($x4, $h4)) {
if (Log::$a) {
__log("Still referenced, do not delete file");
}
return true;
}
return false;
}
function g3($g4, $ey)
{
global $_config;
if ($g4 == "note" and $ey == "new") {
if (is_file(USER_DIR . "new-uploads.psa")) {
$h4 = @unserialize(file_get_contents(USER_DIR . "new-uploads.psa"));
}
} elseif ($g4 == "note") {
sm(
"SELECT `Uploads` FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
$h3 = qm();
$h4 = @unserialize($h3[0]["Uploads"]);
} elseif ($g4 == "tag") {
sm(
"SELECT `Uploads` FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
$h3 = qm();
$h4 = @unserialize($h3[0]["Uploads"]);
}
if (!is_array($h4)) {
$h4 = [];
}
return $h4;
}
function w3($g4, $ey, $h4)
{
global $_config;
if ($g4 == "note" and $ey == "new") {
if (!@e3(USER_DIR . "new-uploads.psa", serialize($h4))) {
return false;
}
} elseif ($g4 == "note") {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Notes` " .
"SET `Uploads`='" .
serialize($h4) .
"' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
} elseif ($g4 == "tag") {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Keywords` " .
"SET `Uploads`='" .
serialize($h4) .
"' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
} else {
return false;
}
if (!is_array($h4)) {
$h4 = [];
}
return $h4;
}
function u3($g4, $ey, $action, $w4)
{
$h4 = [];
if (Log::$a) {
__log(
"Register upload: <" .
$g4 .
", " .
$ey .
", " .
$action .
", " .
$w4 .
">"
);
}
$h4 = g3($g4, $ey);
$h4 = h1($h4, $action, $w4);
return w3($g4, $ey, $h4);
}
function i3($cb, $u4, $v3)
{
($s4 = @unserialize($u4["Uploads"])) or ($s4 = []);
$i4 = l2($v3);
$h4 = h1($s4, "add", $i4);
$h4 = serialize($h4);
if ($h4 != $u4["Uploads"]) {
$u4["Uploads"] = $h4;
fm(bl(), $cb, $u4);
}
}
function e2j_file_upload($parameters = [])
{
global $_config, $_strings;
@nq($_config["path_media"] . PICTURES_DIRNAME);
@chmod(
$_config["path_media"] . PICTURES_DIRNAME,
$_config["uploaded_files_mode"]
);
@nq($_config["path_media"] . VIDEO_DIRNAME);
@chmod(
$_config["path_media"] . VIDEO_DIRNAME,
$_config["uploaded_files_mode"]
);
@nq($_config["path_media"] . AUDIO_DIRNAME);
@chmod(
$_config["path_media"] . AUDIO_DIRNAME,
$_config["uploaded_files_mode"]
);
$dl = ["success" => false];
if (count($_FILES) > 0) {
foreach ($_FILES as $s2) {
if (!$s2["error"]) {
if (Log::$a) {
__log('Ajax file upload: "' . $s2["name"] . '"');
}
$o4 = q2($s2["name"]);
$w = $o4["local-folder"];
$p4 =
(array_key_exists("overwrite", $_GET) and
is_file($w . $s2["name"]));
$cz = false;
$dl["data"]["overwrite"] = (int) $p4;
if (Log::$a) {
__log(
"Ajax file upload: Overwrite is resolved to <" .
(int) $p4 .
">"
);
}
$k4 = j3($s2["name"], $o4["default-filename"]);
if (Log::$a) {
__log("Ajax file upload: Safe name is <" . $k4 . ">");
}
if (is_file($w . $k4)) {
if (
file_get_contents($w . $k4) ==
file_get_contents($s2["tmp_name"])
) {
if (Log::$a) {
__log(
"Ajax file upload: Existing file is the same"
);
}
$cz = true;
} elseif (!$p4) {
$k4 = fd($w, $k4);
}
}
if (!$cz) {
move_uploaded_file($s2["tmp_name"], $w . $k4);
@chmod($w . $k4, $_config["uploaded_files_mode"]);
}
if (Log::$a) {
__log(
'Ajax file upload: Resource type is "' .
$o4["type"] .
'"'
);
}
if ($o4["type"] == "local-image") {
$vz = pathinfo($k4, PATHINFO_EXTENSION);
if (sd($vz, "jpg")) {
$bz = $k4;
} else {
$bz = $k4 . ".jpg";
$bz = fd(
$_config["path_media"] . PICTURES_DIRNAME,
$bz
);
}
$yz = $_config["path_media"] . PICTURES_DIRNAME . $k4;
$nz = $_config["path_media"] . PICTURES_DIRNAME . $bz;
if (Log::$a) {
__log(
'Ajax file upload: Process uploaded image "' .
$yz .
'"' .
' to possibly "' .
$nz .
'"'
);
}
$mz = false;
$nz = e2img_filename_by_processing(
$yz,
$nz,
[
$_config["fit_uploaded_images"],
$_config["fit_uploaded_images"],
],
CROP_NONE,
SCALED_IMAGE_JPG_QUALITY
);
$fz = $s2["size"];
if ($nz !== false) {
if (!sd($nz, $yz)) {
@unlink($yz);
$k4 = $bz;
$fz = stat($nz)["size"];
}
if ($p4) {
@unlink(i2($k4));
}
if (
$dz = e2img_filename_by_processing(
$nz,
i2($k4),
[THUMB_WIDTH, THUMB_HEIGHT],
CROP_NONE,
THUMB_JPG_QUALITY
)
) {
if (
u3(
$parameters["entity"],
$parameters["entity-id"],
"add",
[$k4]
)
) {
if (Log::$a) {
__log(
"Ajax file upload: thumbnail, done as " .
$dz
);
}
list($sz, $az) = e2_getimagesize($dz);
if (Log::$a) {
__log(
"Ajax file upload: image size " .
$sz .
"" .
$az
);
}
if (!$sz) {
$sz = THUMB_WIDTH / 2;
}
if (!$az) {
$az = THUMB_HEIGHT / 2;
}
list($sz, $az) = e2_fit_metrics_to_constraints(
[$sz, $az],
[THUMB_WIDTH / 2, THUMB_HEIGHT / 2]
);
$dl["success"] = true;
$dl["data"]["new-name"] = $k4;
$dl["data"]["filesize"] =
round($fz / 1024) .
" " .
$_strings["gs--kb"];
$dl["data"]["thumb"] = o3($dz);
$dl["data"]["width"] = $sz;
$dl["data"]["height"] = $az;
} else {
if (Log::$a) {
__log(
"Ajax file upload: couldnt register upload"
);
}
@unlink($w . $k4);
@unlink($dz);
$dl["error"]["message"] = _S(
"er--cannot-register-upload"
);
}
} else {
$mz = true;
}
} else {
$mz = true;
}
if ($mz) {
if (Log::$a) {
__log(
"Ajax file upload: couldnt process image for resizing"
);
}
@unlink($w . $k4);
$dl["error"]["message"] = _S(
"er--cannot-create-thumbnail"
);
}
}
if ($o4["type"] == "local-video") {
if (Log::$a) {
__log("Ajax file upload: video, done");
}
$dl["success"] = true;
$dl["data"]["new-name"] = $k4;
$dl["data"]["filesize"] =
round($s2["size"] / 1024) . " " . $_strings["gs--kb"];
$dl["data"]["thumb"] =
SYSTEM_THEME_DIR . VIDEO_ICON_FILENAME;
$dl["data"]["width"] = VIDEO_ICON_WIDTH / 2;
$dl["data"]["height"] = VIDEO_ICON_HEIGHT / 2;
u3($parameters["entity"], $parameters["entity-id"], "add", [
$k4,
]);
}
if ($o4["type"] == "local-audio") {
if (Log::$a) {
__log("Ajax file upload: audio, done");
}
$dl["success"] = true;
$dl["data"]["new-name"] = $k4;
$dl["data"]["filesize"] =
round($s2["size"] / 1024) . " " . $_strings["gs--kb"];
$dl["data"]["thumb"] =
SYSTEM_THEME_DIR . AUDIO_ICON_FILENAME;
$dl["data"]["width"] = AUDIO_ICON_WIDTH / 2;
$dl["data"]["height"] = AUDIO_ICON_HEIGHT / 2;
u3($parameters["entity"], $parameters["entity-id"], "add", [
$k4,
]);
}
} elseif (4 != $s2["error"]) {
$dl["error"]["message"] = ny($s2["error"]);
}
}
} else {
if (Log::$a) {
__log("Ajax file upload error: no files");
}
$dl["error"]["message"] = "No files were received by server";
}
$dl = json_encode($dl);
die($dl);
}
function o3($qz)
{
global $_config;
$lz = strlen($_config["path_media"]);
if ($lz and substr($qz, 0, $lz) == $_config["path_media"]) {
return substr($qz, $lz);
} else {
return AeEnv::$o . $qz;
}
}
function p3()
{
return [
"userpic.original.png",
"userpic.original.jpg",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
];
}
function cy()
{
global $_config;
foreach (p3() as $ud) {
@unlink($_config["path_media"] . USERPIC_DIRNAME . $ud);
}
}
function e2j_userpic_remove()
{
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_settings"));
}
cy();
$dl = json_encode(["success" => true]);
die($dl);
}
function e2j_userpic_upload()
{
global $_config, $_strings;
$dl = ["success" => false];
if (count($_FILES) != 1) {
if (Log::$a) {
__log("Ajax userpic upload error: no or too many files");
}
$dl["error"]["message"] =
$_strings["er--cannot-upload-no-or-too-many-files"];
$dl = json_encode($dl);
die($dl);
}
$s2 = array_pop($_FILES);
if (!$s2["error"]) {
if (Log::$a) {
__log("Ajax userpic upload: <" . $s2["name"] . ">");
}
$zz = pathinfo($s2["name"]);
$vz = strtolower($zz["extension"]);
if ($vz != "png") {
$vz = "jpg";
}
$od = "userpic.original." . $vz;
$id = $_config["path_media"] . USERPIC_DIRNAME;
cy();
move_uploaded_file($s2["tmp_name"], $id . $od);
@chmod($id . $od, $_config["uploaded_files_mode"]);
copy($id . $od, $id . "[email protected]");
e2img_filename_by_processing(
$id . "[email protected]",
$id . "[email protected]",
[$_config["max_image_width"], $_config["max_image_width"]],
CROP_NONE,
$_config["userpic_jpeg_quality"]
);
copy($id . $od, $id . "[email protected]");
$xz = e2img_filename_by_processing(
$id . "[email protected]",
$id . "[email protected]",
[$_config["max_image_width"], $_config["max_image_width"]],
CROP_SQUARE,
$_config["userpic_jpeg_quality"]
);
e2img_filename_by_processing(
$id . $od,
$id . "[email protected]",
[$_config["userpic_size"], $_config["userpic_size"]],
CROP_SQUARE,
$_config["userpic_jpeg_quality"]
);
if ($xz) {
$rz = str_replace($_config["path_media"], "", $xz);
$dl = ["success" => true, "data" => ["new-image-src" => $rz]];
} else {
$dl["error"]["message"] = _S("er--supported-only-png-jpg-gif");
}
} elseif (4 != $s2["error"]) {
$dl["error"]["message"] = ny($s2["error"]);
}
$dl = json_encode($dl);
die($dl);
}
function e2j_file_rename($parameters)
{
global $_strings;
$dl = ["success" => false];
if (
!array_key_exists("file", $_POST) or
!array_key_exists("new-name", $_POST)
) {
$dl = json_encode($dl);
die($dl);
}
$tz = $_POST["file"];
$k4 = $_POST["new-name"];
if (empty($tz) or empty($k4)) {
$dl = json_encode($dl);
die($dl);
}
if (Log::$a) {
__log('Rename "' . $tz . '" to "' . $k4 . '" {');
}
if (dd($tz) !== dd($k4)) {
$jz = pathinfo($tz);
$hz = (string) @$jz["extension"];
$k4 .= "." . $hz;
if (Log::$a) {
__log(
'Cannot change file type while renaming, will rename to "' .
$k4 .
'"'
);
}
}
$gz = q2($tz);
$wz = is_file($gz["local-folder"] . $k4);
if (
$wz and
file_get_contents($gz["local-folder"] . $tz) !==
file_get_contents($gz["local-folder"] . $k4)
) {
if (Log::$a) {
__log("Target file exists and has different content, cancelling");
}
$dl["error"]["message"] =
$_strings["er--cannot-rename-file-exists"] . ": " . $k4;
$dl = json_encode($dl);
die($dl);
}
u3($parameters["entity"], $parameters["entity-id"], "remove", $tz);
if ($wz) {
if (Log::$a) {
__log("Target file exists and is identical, will merge");
}
if (h3($tz)) {
if (Log::$a) {
__log(
"Referenced in another entity, will register under new name with this entity"
);
}
} else {
if (Log::$a) {
__log(
"Not referenced in another entity, will delete and register under new name with this entity"
);
}
$uz = [$gz["local-full-filename"]];
if ($gz["is-generating-thumbnail?"]) {
$uz[] = $gz["local-full-thumb-filename"];
}
foreach ($uz as $iz) {
if (Log::$a) {
__log("Not referenced, deleting " . $iz);
}
@unlink($iz);
}
}
u3($parameters["entity"], $parameters["entity-id"], "add", [$k4]);
} else {
if (h3($tz)) {
if (Log::$a) {
__log("Referenced in another entity, will make a copy");
}
$oz = "copy";
} else {
if (Log::$a) {
__log("Not referenced in another entity, will rename");
}
$oz = "rename";
}
if (@$oz($gz["local-full-filename"], $gz["local-folder"] . $k4)) {
u3($parameters["entity"], $parameters["entity-id"], "add", [$k4]);
if ($gz["is-generating-thumbnail?"]) {
if (Log::$a) {
__log("Will also try to copy/rename a thumbnail");
}
@$oz($gz["local-full-thumb-filename"], i2($k4));
}
} else {
if (Log::$a) {
__log("Error: couldnt " . $oz);
}
$dl = json_encode($dl);
die($dl);
}
}
$dl = ["success" => true];
$dl["data"]["new-name"] = $k4;
$dl = json_encode($dl);
if (Log::$a) {
__log("}");
}
die($dl);
}
function e2j_file_remove($parameters)
{
if (!array_key_exists("file", $_POST)) {
$dl = ["success" => false];
$dl = json_encode($dl);
die($dl);
}
$s2 = $_POST["file"];
$dl = ["success" => true];
$dl = json_encode($dl);
u3($parameters["entity"], $parameters["entity-id"], "remove", $s2);
if (!h3($s2)) {
$o4 = q2($s2);
$uz = [$o4["local-full-filename"]];
if ($o4["is-generating-thumbnail?"]) {
$uz[] = $o4["local-full-thumb-filename"];
}
foreach ($uz as $iz) {
if (Log::$a) {
__log("Not referenced, deleting " . $iz);
}
@unlink($iz);
}
}
die($dl);
}
function vy()
{
global $_config;
if (!$_config["files_total_size_limit"]) {
return false;
}
$pz = 0;
foreach (glob($_config["path_media"] . PICTURES_DIRNAME . "/*") as $s2) {
$ck = stat($s2);
$pz += $ck["size"];
}
foreach (glob($_config["path_media"] . VIDEO_DIRNAME . "/*") as $s2) {
$ck = stat($s2);
$pz += $ck["size"];
}
foreach (glob($_config["path_media"] . AUDIO_DIRNAME . "/*") as $s2) {
$ck = stat($s2);
$pz += $ck["size"];
}
$vk = $_config["files_total_size_limit"];
$bk = j1($pz, $vk);
return [$pz, $vk, $bk];
}
function by($yk)
{
$nk = true;
if (list($pz, $vk, $bk) = $yk) {
$nk = $vk - $pz > 0;
}
return $nk;
}
function yy($yk, $mk = false)
{
$fk = "";
if (list($pz, $vk, $bk) = $yk) {
$yk = [
"used" => round($pz / 1024 / 1024),
"total" => round($vk / 1024 / 1024),
"percent" => $bk,
];
if ($mk or $vk - $pz < 1024 * 1024 * 10) {
if ($pz < $vk) {
$fk = e2l_get_string("gs--used", $yk);
} else {
$fk = e2l_get_string("gs--used-all", $yk);
}
}
}
return $fk;
}
function ny($eq)
{
global $_strings;
if ($eq == UPLOAD_ERR_INI_SIZE) {
$zq = $_strings["er--cannot-upload-file-too-big"];
} elseif ($eq == UPLOAD_ERR_FORM_SIZE) {
$zq = $_strings["er--cannot-upload-file-too-big"];
} else {
$zq = e2l_get_string("er--cannot-upload", ["error" => $eq]);
}
return $zq;
}
function dy($xx)
{
$prefix = "Neasden\\";
if (BUILT) {
$ex = __DIR__ . "/library/neasden/";
} else {
$ex = __DIR__ . "/../library/neasden/";
}
$lz = strlen($prefix);
if (strncmp($prefix, $xx, $lz) !== 0) {
return;
}
$rx = substr($xx, $lz);
$s2 = $ex . str_replace("\\", "/", $rx) . ".php";
if (file_exists($s2)) {
require $s2;
}
}
function sy($tx = null)
{
global $_config, $_lang;
$jx = new Neasden\Configuration();
$jx->baseUrl = AeEnv::$o;
$jx->pathMedia = $_config["path_media"];
$jx->additionalExtensionsFolder = "user/library/neasden/";
$jx->language = $_lang;
$jx->htmlOn = true;
$jx->htmlElementsOpaque = "p ul ol li pre";
$jx->htmlElementsIgnore =
"div blockquote table tr td th thead tbody tfoot caption colgroup col";
$jx->htmlElementsSacred =
"object embed iframe head link script style code textarea";
$jx->htmlBasic = false;
$jx->htmlCodeOn = true;
$jx->htmlCodeWrap = [
'<pre class="e2-text-code"><code class="%s">',
"</code></pre>",
];
$jx->htmlCodeRequireLinks = [
"highlight/highlight.js",
"highlight/highlight.css",
];
$jx->htmlImgSrcPrefix = PICTURES_DIRNAME;
$jx->htmlImgDetect = true;
$jx->groupsOn = true;
$jx->groupsHeadingsChar = "#";
$jx->groupsHeadingsPlus = 1;
$jx->groupsQuotesChar = ">";
$jx->groupsListsChars = ["-", "*"];
$jx->groupsGenericCssClass = "e2-text-generic-object";
$jx->extensions = [
"HR",
"Block",
"AeOldList",
"Table" => ["css-class" => "e2-text-table"],
"Tweet" => ["css-class" => "e2-text-generic-object"],
];
$jx->typographyOn = true;
$jx->typographyQuotes = true;
$jx->typographyMarkup = true;
$jx->typographyAutoHref = true;
$jx->typographyNoFollowHrefs = false;
$jx->typographyUndecoratedLinksCssClass = "nu";
$jx->typographyCleanup = [
" " => "",
"«" => "",
"»" => "",
"„" => "",
"“" => "",
"”" => "",
];
if ($tx === "full" or $tx === "full-rss") {
$jx->htmlOn = true;
$jx->groupsOn = true;
$jx->typographyMarkup = true;
$jx->extensions = array_merge($jx->extensions, [
"MediaTimecodes",
"Picture" => [
"src-prefix" => PICTURES_DIRNAME,
"folder" => PICTURES_DIRNAME,
"css-class" => "e2-text-picture",
"max-width" => $_config["max_image_width"],
],
"Fotorama" => [
"src-prefix" => PICTURES_DIRNAME,
"folder" => PICTURES_DIRNAME,
"css-class" => "e2-text-picture",
"max-width" => $_config["max_image_width"],
],
"Video" => [
"src-prefix" => VIDEO_DIRNAME,
"folder" => VIDEO_DIRNAME,
"css-class" => "e2-text-video",
"max-width" => $_config["max_image_width"],
"getid3-path" =>
SYSTEM_DIR . LIBRARY_DIRNAME . "getid3/getid3.php",
],
"OnlineVideo" => [
"css-class" => "e2-text-video",
"max-width" => $_config["max_image_width"],
"ratio" => 16 / 9,
],
"Audio" => [
"src-prefix" => AUDIO_DIRNAME,
"folder" => AUDIO_DIRNAME,
"css-class" => "e2-text-audio",
"mp3info-path" =>
SYSTEM_DIR . LIBRARY_DIRNAME . "mp3info/mp3info.php",
],
]);
}
if ($tx === "simple" or $tx === "simple-rss") {
$jx->htmlOn = false;
$jx->groupsOn = true;
$jx->typographyMarkup = true;
}
if ($tx === "full-rss" or $tx === "simple-rss") {
$jx->htmlBasic = true;
}
if ($tx === "kavychki") {
$jx->htmlOn = true;
$jx->htmlCodeOn = false;
$jx->groupsOn = false;
$jx->typographyMarkup = false;
$jx->typographyAutoHref = false;
}
return $jx;
}
function ay($e1)
{
$jx = sy("kavychki");
$hx = new Neasden\Model();
$hx->addOpaqueElement($e1);
$gx = new Neasden\Renderer($jx, $hx);
return $gx->getHTML();
}
function qy($wx, $e1)
{
if ($e1 === "") {
return [];
}
if ($wx === "neasden") {
$jx = sy("full");
$ux = new Neasden\Interpreter($jx, $e1);
return $ux->getModel()->getResources();
} else {
return [];
}
}
function ly($wx, $e1, $tx)
{
if (Log::$a) {
__log(
'Format: format with formatter "' .
$wx .
'" in context "' .
$tx .
'"'
);
}
$meta = [];
$eb = "-";
if ($wx === "neasden") {
$jx = sy($tx);
$ux = new Neasden\Interpreter($jx, $e1);
$gx = new Neasden\Renderer($jx, $ux->getModel());
$e1 = $gx->getHTML();
$hx = $ux->getModel();
$eb = $hx->getFlow();
$meta = [
"links-required" => $hx->getLinks(),
"resources-detected" => $hx->getResources(),
];
}
return ["text-final" => $e1, "text-flow" => $eb, "meta" => $meta];
}
function zy($e1, $tx)
{
return ly(DEFAULT_FORMATTER, $e1, $tx);
}
function e2m_frontpage($parameters = [])
{
global $settings, $_strings, $_config;
if (Log::$a) {
__log("Frontpage {");
}
$gn = ys();
$frontpageView = new AePageableNotesView("e2m_frontpage", $parameters);
$frontpageView->setPortionSize($settings["appearance"]["notes_per_page"]);
$frontpageView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$frontpageView->setWantPaging(true);
$frontpageView->setWantNewCommentsCount($gn);
$frontpageView->setWantReadHrefs($_config["count_reads"]);
$frontpageView->setWantControls($gn and !@$_config["read_only"]);
$frontpageView->setWantHiddenTags($gn);
$frontpageView->setWantRelatedNotes(true);
if (CACHE_FRONTPAGE and $frontpageView->isFirstPage()) {
if ($gn) {
$frontpageView->setCacheFilename(
USER_DIR . CACHE_FILENAME_FRONTPAGE_AUTHOR
);
} else {
$frontpageView->setCacheFilename(
USER_DIR . CACHE_FILENAME_FRONTPAGE
);
}
}
$frontpageView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
df($gn) .
"ORDER BY `Stamp` DESC"
);
$ss = ev();
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => "",
"notes" => $frontpageView->getNotesCTree(),
"pages" => $frontpageView->getPagesCTree(),
"frontpage?" => $frontpageView->isFirstPage(),
];
if (
!$frontpageView->isExistingPage() and
!$frontpageView->isFirstPageOfEmptyView()
) {
return e2m_error404();
}
if (Log::$a) {
__log("} // Frontpage");
}
return $vb;
}
abstract class E2GIP
{
protected $gip_cookie_name = "gip";
protected $gip_token_cookie_name = "gip_access_token";
protected $gip_token = null;
abstract public function get_auth_url();
abstract public static function get_profile_url($ey, $ix);
abstract public function callback();
const PHP_VERSION_VK_FEATURE = 70100;
public static function set_session_data($yn, $vv)
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION[$yn] = $vv;
}
public static function get_session_data($yn, $ox = false)
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION[$yn])) {
return null;
}
$vv = $_SESSION[$yn];
if ($ox) {
unset($_SESSION[$yn]);
}
return $vv;
}
public function get_config($yn)
{
$px = "gips/" . $this->type . ".json";
$ll = false;
foreach ([USER_DIR, INSTANCE_DIR, SYSTEM_DIR] as $ce) {
if (is_file($ce . $px)) {
$ll = @file_get_contents($ce . $px);
break;
}
}
if ($ll !== false) {
$vb = json_decode($ll, true, 512, JSON_BIGINT_AS_STRING)[$yn];
if ($vb) {
return $vb;
}
}
return null;
}
public function get_callback_url()
{
return eq("e2m_gip_sign_in_callback", ["provider" => $this->type]);
}
protected function get_proxy_param()
{
global $settings;
$ve = DEFAULT_LANGUAGE;
if (array_key_exists("language", $settings)) {
$ve = $settings["language"];
}
return "?language=" .
$ve .
"&type=" .
$this->type .
"&callback_url=" .
urlencode($this->get_callback_url());
}
public function get_gip_session_data()
{
global $_config;
$be = $this->gip_token
? $this->gip_token
: $_COOKIE[x1($this->gip_token_cookie_name)];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"GIPsSessions` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `GIP` = '" .
$this->type .
"' " .
"AND `SessionToken` = '" .
lm($be) .
"' " .
"ORDER BY `ID` DESC LIMIT 1",
"get GIP session data"
);
$h3 = qm();
return $h3 ? $h3[0] : [];
}
public function is_logged_in()
{
if (
empty($_COOKIE[x1($this->gip_cookie_name)]) ||
!in_array($_COOKIE[x1($this->gip_cookie_name)], ky()) ||
$_COOKIE[x1($this->gip_cookie_name)] != $this->type ||
empty($_COOKIE[x1($this->gip_token_cookie_name)])
) {
return false;
}
$zb = $this->get_gip_session_data();
return (bool) $zb;
}
protected function save_session(
$ey,
$name,
$accessToken,
$ye = "",
$userEmail = "",
$userLink = ""
) {
$mf = time();
mm(
bl(),
"GIPsSessions",
[
"GIP" => $this->type,
"GIPAuthorID" => $ey,
"AuthorName" => $name,
"AuthorEmail" => $userEmail,
"AuthorProfileLink" => $userLink,
"SessionToken" => $accessToken,
"Stamp" => $mf,
],
"INSERT",
"ON DUPLICATE KEY UPDATE " .
'`SessionToken` = "' .
lm($accessToken) .
'", ' .
'`AuthorName` = "' .
lm($name) .
'", ' .
'`Stamp` = "' .
$mf .
'"'
);
e1($this->gip_cookie_name, $this->type);
e1($this->gip_token_cookie_name, $accessToken);
if (isset($userEmail) && !empty($userEmail)) {
e1("commenter_email", $userEmail);
}
$this->gip_token = $accessToken;
}
public static function get_logout_key()
{
if ($ne = self::get_session_data("logout_key")) {
return $ne;
}
$ne = md5(microtime());
self::set_session_data("logout_key", $ne);
return $ne;
}
public static function is_valid_logout_key($yn)
{
$me = self::get_session_data("logout_key", true);
if (empty($me) || empty($yn) || $me != $yn) {
return false;
}
return true;
}
public function logout()
{
global $_config;
e1($this->gip_cookie_name);
e1($this->gip_token_cookie_name);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"GIPsSessions` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `GIP` = '" .
$this->type .
"' " .
"AND `SessionToken` = '" .
lm($_COOKIE[x1($this->gip_token_cookie_name)]) .
"'",
"logout"
);
}
public function get_avatar_size()
{
return AVATAR_SIZE;
}
public function save_avatar($ey, $fe)
{
global $_config;
if (!preg_match("/^https?\:\/\//i", $fe)) {
return;
}
$fe = str_replace("\0", "", $fe);
$ey = preg_replace("/[^a-zA-Z0-9._-]/", "", $ey);
$ey = substr($ey, 0, 64);
@nq($_config["path_media"] . AVATARS_DIRNAME);
@chmod(
$_config["path_media"] . AVATARS_DIRNAME,
$_config["uploaded_files_mode"]
);
$od =
$_config["path_media"] .
AVATARS_DIRNAME .
$this->type .
"-" .
$ey .
".jpg";
if ($de = file_get_contents($fe)) {
file_put_contents($od, $de);
}
return $od;
}
}
function e2m_gip_sign_in($zb)
{
$type = $zb["provider"];
$se = ey($type);
if (!$se) {
k1();
}
header("Location: " . $se->get_auth_url());
die();
}
function e2m_gip_sign_in_callback($zb)
{
$type = $zb["provider"];
$se = ey($type);
if (!$se) {
return e2m_error404();
}
$ae = $se->callback();
if (!$ae) {
return e2m_error404();
}
echo "<script>";
$y1 = $se->get_gip_session_data();
$qe = [
"name" => $y1["AuthorName"],
"gipIcon" => _SVG($type),
"logoutUrl" => eq("e2m_gip_sign_out", [
"provider" => E2GIP::get_logout_key(),
]),
];
echo "window.opener.oauthAuthorized(" . json_encode($qe) . ");";
echo "window.close();</script>";
die();
}
function e2m_gip_sign_out($zb)
{
$ne = $zb["provider"];
if (!E2GIP::is_valid_logout_key($ne)) {
return e2m_error404();
}
$se = jy();
if ($se) {
$se->logout();
}
k1();
}
function ky()
{
global $_config;
static $ga = null;
if ($ga !== null) {
return $ga;
}
$le = (string) @$_config["sign_in_with"];
$ze = "|twitter|facebook|vk|telegram|";
$ke = SYSTEM_DIR . "gips/";
$ga = [];
foreach (explode(",", $le) as $xe) {
$xe = trim($xe);
if ($xe == "vkontakte") {
$xe = "vk";
}
if (!strstr($ze, "|" . $xe . "|")) {
continue;
}
if (!is_file($ke . $xe . ".php")) {
continue;
}
if (in_array($xe, $ga)) {
continue;
}
if ($xe === "vk" and PHP_VERSION_ID < E2GIP::PHP_VERSION_VK_FEATURE) {
continue;
}
$ga[] = $xe;
}
return $ga;
}
function xy($type)
{
return "E2GIP" . ucfirst($type);
}
function ey($type)
{
if (!in_array($type, ky())) {
return false;
}
$ee = xy($type);
$se = new $ee();
return $se;
}
function ry($type)
{
return eq("e2m_gip_sign_in", ["provider" => $type]);
}
function ty($type = "")
{
$re = !$type ? ky() : [$type];
foreach ($re as $type) {
$se = ey($type);
if ($se && $se->is_logged_in()) {
return true;
}
}
return false;
}
function jy()
{
foreach (ky() as $type) {
$se = ey($type);
if ($se && $se->is_logged_in()) {
return $se;
}
}
return false;
}
function hy()
{
foreach (ky() as $type) {
$se = ey($type);
if ($se && $se->is_logged_in()) {
return $type;
}
}
return false;
}
function gy($type, $ey, $ix)
{
$ee = xy($type);
if (class_exists($ee)) {
return $ee::get_profile_url($ey, $ix);
} else {
return false;
}
}
function wy($type)
{
$se = ey($type);
if (!$se || !$se->is_logged_in()) {
return false;
}
return $se->get_gip_session_data();
}
function uy($xx)
{
$od =
SYSTEM_DIR .
"gips/" .
strtolower(str_replace("E2GIP", "", $xx)) .
".php";
if (is_file($od)) {
require $od;
}
}
function e2s_notify()
{
global $_config;
if (!$_config["holborn"]) {
die();
}
$te = @$_GET["src"];
if ($te == "") {
if (Log::$a) {
__log("Holborn: No src URL");
}
die();
}
$ll = file_get_contents($te);
$ll = cn($ll);
$je = json_decode($ll, true);
if (!$je) {
if (Log::$a) {
__log(
"Holborn: No meaningful info from " .
$te .
" (" .
json_last_error() .
")"
);
}
if ($he = oy($te)) {
if (Log::$a) {
__log("Holborn: Delete note with ID " . $he["ID"]);
}
gm($he["ID"]);
}
die();
}
iy($je, $te);
}
function e2m_sources($parameters)
{
global $_config;
if (!$_config["holborn"]) {
return e2m_error404();
}
$ge = $_GET["ord"];
$we = "";
if (@$ge[0] == "!") {
$ge = substr($ge, 1);
$we = " DESC";
}
if (!$ge) {
$ge = "ID";
}
$ge = "`" . lm($ge) . "`";
sm(
"SELECT S.*, " .
"REPLACE(REPLACE(REPLACE(S.`URL`, 'http://', ''), 'https://', ''), 'www.', '') AS _URLX, " .
"COUNT(N.`ID`) AS NotesCount, " .
"MAX(N.`Stamp`) AS LastNoteStamp " .
"FROM `" .
$_config["db_table_prefix"] .
"Sources` AS S, " .
" `" .
$_config["db_table_prefix"] .
"Notes` AS N " .
"WHERE S.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND N.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND S.`ID` = N.`SourceID`" .
"GROUP BY S.`ID` " .
"ORDER BY " .
$ge .
" " .
$we .
" " .
"LIMIT 100"
);
$h3 = qm();
foreach ($h3 as $vl) {
$ue = $vl["ID"];
if ($vl["ID"] != $vl["TrueID"]) {
$ue = "<s>" . $ue . "</s><br />=" . $vl["TrueID"];
}
$source = [
"id" => $ue,
"userpic-href" => $vl["PictureURL"],
"href" => $vl["URL"],
"href-display" => str_replace("/", "/<wbr>", $vl["URL"]),
"href-filtered" => str_replace("/", "/<wbr>", $vl["_URLX"]),
"title" => $vl["Title"],
"author" => $vl["AuthorName"],
"true?" => $vl["ID"] == $vl["TrueID"],
"whitelisted?" => (bool) $vl["IsWhiteListed"],
"trusted?" => (bool) $vl["IsTrusted"],
"notes-count" => $vl["NotesCount"],
"latest-note-time" => [$vl["LastNoteStamp"], 0],
];
if (!$vl["IsTrusted"]) {
$source["trust-url"] = eq("e2m_source_trust", [
"source" => $vl["ID"],
]);
}
if ($vl["IsTrusted"]) {
$source["premoderate-url"] = eq("e2m_source_premoderate", [
"source" => $vl["ID"],
]);
}
$source["ban-url"] = eq("e2m_source_ban", ["source" => $vl["ID"]]);
$source["forget-url"] = eq("e2m_source_forget", [
"source" => $vl["ID"],
]);
$ie[] = $source;
}
$vb = ["title" => "Sources", "heading" => "Sources"];
if (count($ie)) {
$vb["sources"] = $ie;
} else {
$vb["nothing"] = "No sources";
}
return $vb;
}
function e2m_source_trust($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Sources " .
"SET `IsWhitelisted`=1, `IsTrusted`=1 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"trust source"
);
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Notes " .
"SET `IsPublished`=1 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`=" .
$oe,
"publish all notes from the just trusted source"
);
cb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
@unlink(USER_DIR . CACHE_FILENAME_INDEXED_FLAG);
z1();
}
function e2m_source_premoderate($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Sources " .
"SET `IsTrusted`=0 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"distrust source, set to premoderation"
);
cb();
z1();
}
function e2m_source_ban($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Sources " .
"SET `IsWhiteListed`=0, `IsTrusted`=0 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"ban source"
);
sm(
"DELETE FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`=" .
$oe,
"delete all notes from the just banned source"
);
cb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
z1();
}
function e2m_source_forget($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"DELETE FROM " .
$_config["db_table_prefix"] .
"Sources " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"forget source"
);
sm(
"DELETE FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`=" .
$oe,
"delete all notes from the just forgotten source"
);
cb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
z1();
}
function iy($pe, $te)
{
global $_config;
if (!array_key_exists("author", $pe)) {
$pe["author"] = $pe["authors"][0];
}
$c6 = vn([
"author" => $pe["author"]["name"],
"title" => $pe["title"],
"href" => $pe["author"]["url"],
"userpic-href" => $pe["author"]["avatar"],
]);
if (!$c6["IsWhiteListed"]) {
return;
}
if (
preg_match("/\+(\d\d)\:(\d\d)/", $pe["items"][0]["date_published"], $v6)
) {
$t3 = $v6[1] * SECONDS_IN_AN_HOUR + $v6[2] * SECONDS_IN_A_MINUTE;
}
($b6 = @$pe["items"][0]["_e2_data"]) or ($b6 = []);
$b6 = json_encode($b6);
$y6 = $c6["IsTrusted"];
$databaseConfiguration = bl();
$zy = [
"Title" => $pe["items"][0]["title"],
"Text" => $pe["items"][0]["content_html"],
"FormatterID" => "raw",
"OriginalAlias" => "",
"Uploads" => "",
"Stamp" => strtotime($pe["items"][0]["date_published"]),
"Offset" => (int) $t3,
"IsDST" => 0,
"LastModified" => strtotime($pe["items"][0]["date_modified"]),
"IsCommentable" => 0,
"IsPublished" => $y6,
"IsExternal" => 1,
"SourceID" => $c6["ID"],
"SourceNoteID" => $pe["items"][0]["id"],
"SourceNoteURL" => $pe["items"][0]["url"],
"SourceNoteJSONURL" => $te,
"SourceNoteData" => $b6,
];
$note_id = $pe["items"][0]["id"];
if ($he = py($c6["ID"], $note_id)) {
$zy["ID"] = $he["ID"];
fm($databaseConfiguration, "Notes", $zy);
} else {
$zy = mm($databaseConfiguration, "Notes", $zy);
}
if ($y6) {
if (xd($zy)) {
$zy["IsIndexed"] = "1";
fm(bl(), "Notes", $zy);
}
}
$n6 = @$pe["items"][0]["tags"];
if (is_array($n6)) {
ya($databaseConfiguration, $zy["ID"], $n6);
}
e2_drop_caches_for_note_($zy["ID"], $y6);
if ($_config["backup_automatically"]) {
zm();
}
}
function oy($te)
{
global $_config;
sm(
"SELECT `ID` FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceNoteJSONURL`='" .
lm($te) .
"' " .
"LIMIT 1",
"get note ID by source JSON URL"
);
$h3 = qm();
return $h3[0];
}
function py($oe, $m6)
{
global $_config;
sm(
"SELECT `ID` FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`= '" .
$oe .
"' " .
"AND `SourceNoteID`= '" .
$m6 .
"' " .
"LIMIT 1",
"get note ID by source ID and source note ID"
);
$h3 = qm();
return $h3[0];
}
function cn($ll)
{
for ($gb = 0; $gb <= 31; ++$gb) {
$ll = str_replace(chr($gb), "", $ll);
}
$ll = str_replace(chr(127), "", $ll);
if (0 === strpos(bin2hex($ll), "efbbbf")) {
$ll = substr($ll, 3);
}
return $ll;
}
function vn($f6)
{
global $_config;
$d6 = false;
sm(
"SELECT * FROM " .
$_config["db_table_prefix"] .
"Sources " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `URL`= '" .
$f6["href"] .
"' " .
"LIMIT 1",
"get source record by the URL from blog info"
);
$h3 = qm();
if (count($h3)) {
$d6 = $h3[0];
if ($d6["ID"] != $d6["TrueID"]) {
sm(
"SELECT * FROM " .
$_config["db_table_prefix"] .
"Sources " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`= '" .
$d6["TrueID"] .
"' " .
"LIMIT 1",
"get true source record by using the TrueID of just found record"
);
$h3 = qm();
if (count($h3)) {
$d6 = $h3[0];
}
}
}
$c6 = [
"Title" => $f6["title"],
"AuthorName" => $f6["author"],
"PictureURL" => $f6["userpic-href"],
];
if ($d6 !== false) {
if (
$d6["Title"] !== $f6["title"] or
$d6["AuthorName"] !== $f6["author"] or
$d6["PictureURL"] !== $f6["userpic-href"]
) {
$c6["ID"] = $d6["ID"];
fm(bl(), "Sources", $c6);
}
return $d6;
} else {
$c6["URL"] = $f6["href"];
$c6["IsWhiteListed"] = 1;
$c6["IsTrusted"] = 0;
$c6 = mm(bl(), "Sources", $c6);
$c6["TrueID"] = $c6["ID"];
fm(bl(), "Sources", $c6);
return $c6;
}
}
function bn($zy)
{
global $_config;
$ma = [];
if (@$zy["IsExternal"]) {
if (array_key_exists("SourceID", $zy)) {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Sources` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
$zy["SourceID"] .
"'",
"get source by id"
);
$kb = qm();
$ma["source"] = $kb[0]["Title"];
$ma["source-id"] = (int) $zy["SourceID"];
$ma["source-true-id"] = (int) $kb[0]["TrueID"];
$ma["source-whitelisted?"] = (bool) $kb[0]["IsWhiteListed"];
$ma["source-trusted?"] = (bool) $kb[0]["IsTrusted"];
if (!$kb[0]["IsTrusted"]) {
$ma["source-trust-url"] = eq("e2m_source_trust", [
"source" => $zy["SourceID"],
]);
}
if ($kb[0]["IsTrusted"]) {
$ma["source-premoderate-url"] = eq("e2m_source_premoderate", [
"source" => $zy["SourceID"],
]);
}
$ma["source-ban-url"] = eq("e2m_source_ban", [
"source" => $zy["SourceID"],
]);
$ma["source-forget-url"] = eq("e2m_source_forget", [
"source" => $zy["SourceID"],
]);
$ma["author"] = $kb[0]["AuthorName"];
$ma["author-href"] = $kb[0]["URL"];
$ma["userpic-href"] = $kb[0]["PictureURL"];
}
if (
array_key_exists("SourceNoteURL", $zy) and
@$zy["SourceNoteURL"] != ""
) {
$ma["href-external"] = $zy["SourceNoteURL"];
}
}
return $ma;
}
function e2img_filename_by_processing($s6, $a6, $q6, $l6, $z6)
{
global $_config;
if (Log::$a) {
__log('Process image: "' . $s6 . '" -> "' . $a6 . '"');
}
if (!is_file($s6)) {
return false;
}
$k6 = stat($s6)["size"];
if (!vd($s6)) {
if (Log::$a) {
__log("Process image: SVG, no processing");
}
return $s6;
}
if (is_file($a6) and filesize($a6) > 0 and !sd($s6, $a6)) {
if (Log::$a) {
__log("Process image: Already exists");
}
return $a6;
}
$x6 = pathinfo($a6);
if (!@nq($x6["dirname"])) {
if (Log::$a) {
__log(
"Process image: Cant create directory <" .
$x6["dirname"] .
">"
);
}
return false;
}
if (Log::$a) {
__log("Process image: Detecting image type");
}
$type = e2img__type_of_file($s6);
if (!$type) {
return false;
}
$e6 = "imagecreatefrom" . $type;
if (!function_exists($e6)) {
if (Log::$a) {
__log("Process image: Function does not exist (" . $e6 . ")");
}
return false;
}
if (Log::$a) {
__log("Process image: Opening original image (" . $e6 . ")");
}
$r6 = call_user_func($e6, $s6);
if (!$r6) {
return false;
}
if ($t6 = e2img__orientation_of_file($s6)) {
if (Log::$a) {
__log("Process image: Needs orientation fix");
}
$r6 = e2img__res_rotate($r6, -$t6);
}
$j6 = [imagesx($r6), imagesy($r6)];
$h6 = $j6;
$g6 = [0, 0, 0, 0];
if ($l6 == CROP_SQUARE) {
if (Log::$a) {
__log("Process image: Needs crop");
}
list($h6, $g6) = e2img__crop_metrics_to_square($h6);
}
$h6 = e2_fit_metrics_to_constraints($h6, $q6);
if ($t6 === 0 and $h6 === $j6) {
if (Log::$a) {
__log("Process image: No changes necessary, leaving original");
}
return $s6;
}
if (Log::$a) {
__log(var_export($h6, true));
}
if (Log::$a) {
__log(var_export($g6, true));
}
$w6 = e2img__create_copy_resampled($r6, $h6, $g6, $type);
imagejpeg($w6, $a6, $z6);
if (!is_file($a6)) {
if (Log::$a) {
__log("Process image: File not created by imagejpeg");
}
return false;
}
if ($a6 !== $s6) {
if ($t6 === 0) {
$u6 = stat($a6)["size"];
if ($u6 >= $k6) {
if (Log::$a) {
__log(
"Process image: Conversion to JPEG made file bigger, back up"
);
}
@unlink($a6);
$a6 = $s6;
}
}
}
@chmod($a6, $_config["uploaded_files_mode"]);
if (Log::$a) {
__log("Process image: Done");
}
return $a6;
}
function e2img__create_copy_resampled($r6, $h6, $g6, $type)
{
list($i6, $o6) = $h6;
list($p6, $cr, $vr, $br) = $g6;
$w6 = imagecreatetruecolor($i6, $o6);
if ($type === "png") {
imagefill($w6, 0, 0, imagecolorallocate($w6, 255, 255, 255));
imagealphablending($w6, true);
}
$yr = imagesx($r6);
$nr = imagesy($r6);
imagecopyresampled(
$w6,
$r6,
0,
0,
0 + $p6,
0 + $cr,
$i6,
$o6,
$yr - $vr,
$nr - $br
);
imageinterlace($w6, 1);
return $w6;
}
function e2img__type_of_file($od)
{
$mr = @getimagesize($od);
if (!$mr) {
return false;
}
if (defined("IMAGETYPE_GIF") and $mr[2] == IMAGETYPE_GIF) {
return "gif";
}
if (defined("IMAGETYPE_JPEG") and $mr[2] == IMAGETYPE_JPEG) {
return "jpeg";
}
if (defined("IMAGETYPE_PNG") and $mr[2] == IMAGETYPE_PNG) {
return "png";
}
if (defined("IMAGETYPE_WEBP") and $mr[2] == IMAGETYPE_WEBP) {
return "webp";
}
return false;
}
function e2img__orientation_of_file($od)
{
if (!function_exists("exif_read_data")) {
return 0;
}
if (($fr = @exif_read_data($od)) === false) {
return 0;
}
if (@$fr["Orientation"] == 3) {
return -180;
}
if (@$fr["Orientation"] == 6) {
return -270;
}
if (@$fr["Orientation"] == 8) {
return -90;
}
return 0;
}
function e2img__res_rotate($dr, $t6)
{
$sr = imagerotate($dr, $t6, 0);
if ($sr !== false) {
imagedestroy($dr);
$dr = $sr;
}
return $dr;
}
function e2_fit_metrics_to_constraints($ar, $q6)
{
if ($q6 === false) {
$q6 = [0, 0];
}
list($sz, $az) = $ar;
list($qr, $lr) = $q6;
$zr = [1];
if ($qr) {
$zr[] = $qr / $sz;
}
if ($lr) {
$zr[] = $lr / $az;
}
$kr = min($zr);
if ($kr < 1) {
$sz = (int) round($sz * $kr);
$az = (int) round($az * $kr);
}
return [$sz, $az];
}
function e2_getimagesize_jpeg($od)
{
$xr = @fopen($od, "r");
if ($xr === false) {
throw new \RuntimeException(error_get_last()["message"]);
}
try {
if (!flock($xr, LOCK_SH)) {
throw new \RuntimeException("Cannot lock the file: " . $od);
}
$m2 = fread($xr, 2);
if ($m2 !== "\xFF\xD8") {
throw new \RuntimeException("Unknown format: " . $od);
}
for (;;) {
$er = @unpack("H4segment/nlen", fread($xr, 4));
if ($er === false) {
throw new \RuntimeException("Unknown format: " . $od);
}
$lz = $er["len"];
$rr = $er["segment"];
if (preg_match("/^ffc[0-3]/", $rr)) {
$tr = @unpack("Cbits/nheight/nwidth", fread($xr, $lz - 2));
if ($tr === false) {
throw new \RuntimeException("Unknown format: " . $od);
}
return [$tr["width"], $tr["height"]];
}
if (fseek($xr, $lz - 2, SEEK_CUR) !== 0) {
throw new \RuntimeException(
"Cannot find start of frame: " . $od
);
}
}
} finally {
fclose($xr);
}
}
function e2_getimagesize($od)
{
$sz = $az = 0;
if (p2($od)) {
try {
list($sz, $az) = e2_getimagesize_jpeg($od);
} catch (\Exception $e) {
list($sz, $az) = getimagesize($od);
}
} elseif (vd($od)) {
list($sz, $az) = getimagesize($od);
} elseif (yd($od)) {
try {
require_once SYSTEM_DIR . LIBRARY_DIRNAME . "getid3/getid3.php";
$mr = new getid3();
$mr = $mr->analyze($od);
$sz = $mr["video"]["resolution_x"];
$az = $mr["video"]["resolution_y"];
} catch (\Exception $e) {
}
} elseif (bd($od)) {
if (function_exists("simplexml_load_string")) {
$jr = simplexml_load_string(file_get_contents($od));
if ($jr) {
$hr = $jr->attributes();
list($sz, $az) = [(string) $hr->width, (string) $hr->height];
}
}
}
if (substr($od, strrpos($od, ".") - 3, 3) == "@2x") {
$sz = (int) floor($sz / 2);
$az = (int) floor($az / 2);
}
$gr = round($az > 0 ? $sz / $az : 1, 2);
$wr = round($sz > 0 ? $az / $sz : 1, 2);
return [$sz, $az, $gr, $wr];
}
function e2img__crop_metrics_to_square($ar)
{
$ur = $ir = $or_ = $pr = 0;
list($sz, $az) = $ar;
if ($sz > $az) {
$or_ = $sz - $az;
$ur = floor($or_ / 2);
$az = $sz;
} elseif ($sz < $az) {
$pr = $az - $sz;
$ir = floor($or_ / 2);
$sz = $az;
}
$g6 = [$ur, $ir, $or_, $pr];
$ct = [$sz, $az];
return [$ct, $g6];
}
function e2m_install()
{
global $_strings, $_config;
kf(DEFAULT_TEMPLATE);
$vb = [];
if (Log::$a) {
__log("Installer: not installed, present user with form");
}
$vt["server"] = @$_COOKIE[x1("install_db_server")];
$vt["user_name"] = @$_COOKIE[x1("install_db_user_name")];
$vt["passw"] = ks(@$_COOKIE[x1("install_db_passw")]);
$vt["name"] = @$_COOKIE[x1("install_db_name")];
$vb = [
"title" => $_strings["pt--install"],
"heading" => $_strings["pt--install"],
"form-install" => [
"form-action" => eq("e2s_install"),
"form-check-db-config-action" => eq("e2j_check_db_config"),
"form-list-databases-action" => eq("e2j_list_databases"),
"submit-text" => $_strings["fb--begin"],
"db-server" => htmlspecialchars(
@$vt["server"] ? $vt["server"] : "localhost"
),
"db-user" => htmlspecialchars(
@$vt["user_name"] ? $vt["user_name"] : "root"
),
"db-password" => "",
"db-database" => htmlspecialchars((string) @$vt["name"]),
],
];
return $vb;
}
function yn()
{
static $se = null;
if ($se === null) {
($se = @unserialize(
@file_get_contents(INSTANCE_DIR . "instance.psa")
)) or ($se = null);
}
return $se;
}
function nn($bt)
{
static $se = null;
$se = yn();
$se["version"] = $bt;
if (e3(INSTANCE_DIR . "instance.psa", serialize($se))) {
return $se;
} else {
die("Cannot instantiate v" . $bt . ": probably permission denied");
}
}
function e2s_instantiate($parameters)
{
global $_strings;
if (yn() !== null) {
die('Remove the file "' . INSTANCE_DIR . 'instance.psa" first');
} else {
if (is_numeric($parameters["version"])) {
if (nn($parameters["version"])) {
hb(
$_strings["gs--instantiated-version"] .
" v" .
$parameters["version"],
E2E_MESSAGE
);
z1(eq("e2m_frontpage", ["page" => 1]));
}
}
}
die("Could not create instance of engine");
}
function e2_install($databaseConfiguration, $zb)
{
global $_strings, $_config, $settings;
if (yn() !== null and bl() !== null and vs()) {
throw new AeInstallAlreadyInstalledException(
"Instance already created and db params set"
);
}
$databaseConfiguration->setPrefix($_config["db_table_prefix"]);
$databaseConfiguration->setSubset($_config["db_table_subset"]);
if (array_key_exists("db_plain_password", $zb)) {
$databaseConfiguration->password = zs($zb["db_plain_password"]);
}
if ($_config["log_installs"]) {
Log::$a = true;
if (Log::$a) {
qn('install-$');
}
}
if (Log::$a) {
__log("Installer: force directories");
}
AeFileManager::forceAllDirectories();
if (Log::$a) {
__log("Installer: write password hash");
}
if (
!@e3(USER_DIR . "password-hash.psa", serialize(sha1($zb["password"])))
) {
throw new AeNotSavedException();
}
$settings["db"] = $databaseConfiguration->getDatabaseParamsArray();
$settings["template"] = DEFAULT_TEMPLATE;
$settings["language"] = DEFAULT_LANGUAGE;
dm($databaseConfiguration, "check database during installation");
$yt = pn($databaseConfiguration);
$nt = false;
if ($yt["occupied"]) {
if ($yt["migrateable"] and $zb["allow_migration"]) {
$nt = true;
if (Log::$a) {
__log("Installer: data exists and migrateable");
}
} else {
if (Log::$a) {
__log("Installer: incomplete data in the database");
}
throw new AeInstallDatabaseOccupiedException(
"Database already has some data"
);
}
}
if ($nt) {
if (Log::$a) {
__log("Installer: no need to create tables, will migrate");
}
try {
wn($databaseConfiguration);
} catch (AeMySQLException $e) {
v3($e, "Could not migrate");
hb($_strings["er--double-check-db-params"]);
}
wd($databaseConfiguration);
} else {
if (Log::$a) {
__log("Installer: create tables");
}
foreach (AeModel::unprefixedCoreTablesNames() as $cb) {
nm($databaseConfiguration, $cb);
}
}
if (Log::$a) {
__log("Installer: write settings");
}
if (
!@e3(USER_DIR . "settings.json", json_encode($settings, E2_JSON_STYLE))
) {
throw new AeNotSavedException();
}
if (Log::$a) {
__log("Installer: search index");
}
$mt = jd(bl());
try {
$mt->erase();
} catch (\S2\Rose\Exception\RuntimeException $e) {
if (Log::$a) {
__log("Installer: Rose not available");
}
}
e2_drop_all_kinds_of_cache();
ld(USER_DIR);
rm($databaseConfiguration);
if (Log::$a) {
__log("Installer: instantiate");
}
nn(E2_VERSION);
if (Log::$a) {
__log("Installer: complete");
}
}
function e2s_install()
{
global $_strings, $_db, $_config;
if (yn() !== null and bl() !== null and vs()) {
z1();
}
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$_POST,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
foreach ($databaseConfiguration->getDatabaseParamsArray() as $k3 => $x3) {
e1("install_db_" . $k3, $x3);
}
if (
!array_key_exists("password", $_POST) or
trim($_POST["password"]) == ""
) {
hb($_strings["er--no-password-entered"], E2E_USER_ERROR);
z1(eq("e2m_frontpage"));
}
$ft = trim($_POST["password"]);
@session_start();
$dt = false;
try {
e2_install($databaseConfiguration, [
"allow_migration" => true,
"password" => $ft,
]);
$dt = true;
} catch (AeMySQLCannotConnectException $e) {
hb(
$_strings["er--cannot-connect-to-db"] .
":<br />" .
mysqli_connect_error() .
" (" .
mysqli_connect_errno() .
")"
);
} catch (AeMySQLTooOldException $e) {
hb(
e2l_get_string("er--dbs-version-too-old", [
"dbs" => $_db["software"],
"v1" => $_db["version"],
"v2" => $_db["version-minimum"],
])
);
} catch (AeMySQLException $e) {
hb(
$_strings["er--cannot-find-db"] . " " . $databaseConfiguration->name
);
} catch (AeInstallDatabaseOccupiedException $e) {
hb($_strings["er--db-data-incomplete-install"]);
} catch (AeNotSavedException $e) {
hb($_strings["er--settings-not-saved"], E2E_PERMISSIONS_ERROR);
} catch (AeInstallException $e) {
}
mn();
if (!$dt) {
z1(eq("e2m_frontpage", ["page" => 1]));
}
$st["sessions"] = [
[
"stamp" => time(),
"remote_ip" => pd(),
"key_hash" => bs(true),
"ua" => $_SERVER["HTTP_USER_AGENT"],
],
];
if (!ms($st)) {
hb($_strings["er--cannot-write-auth-data"], E2E_PERMISSIONS_ERROR);
}
vv(eq("e2s_bsi_step", []));
z1();
}
function mn()
{
global $_config;
if (strpos($_SERVER["SERVER_SOFTWARE"], "Apache") !== 0) {
return;
}
if (Log::$a) {
__log("Running on Apache");
}
$at = SYSTEM_DEFAULTS_DIR . "default.htaccess";
$qt = false;
if (!is_file($at)) {
echo "File not found: " .
$at .
". Please use the full Aegea installation package.";
die();
}
$lt = file_get_contents($at);
foreach (
["custom_htaccess_directives", "custom_htaccess_rewrites"]
as $zt
) {
if ((string) @$_config[$zt] !== "") {
$lt = str_replace(
"##" . $zt . "##\r\n",
(string) @$_config[$zt],
$lt
);
} else {
$lt = str_replace("\r\n##" . $zt . "##\r\n", "", $lt);
}
}
if (is_file(".htaccess")) {
if (Log::$a) {
__log("There is an .htaccess file in the installation directory");
}
$kt = file_get_contents(".htaccess");
if ($kt != $lt) {
$qt = true;
$xt = $et = ".htaccess.old";
$rt = 1;
while (is_file($et)) {
$et = $xt . "." . $rt++;
}
if (Log::$a) {
__log("Existing .htaccess wrong, backing up as <" . $et . ">");
}
if (!@rename(".htaccess", $et)) {
if (Log::$a) {
__log("Installer: fuck");
}
echo 'Looks like you are using Apache and have put an incorrect ".htaccess" file in the installation directory. Additionally, the installer was not able to back up your existing ".htaccess" file in order to replace it with the correct one. Please use the full E2 installation package and grant write access on the installation target directory, all the files and subdirectories.';
die();
}
}
} else {
$qt = true;
}
if ($qt) {
if (Log::$a) {
__log("Writing a correct .htaccess file");
}
if (!@file_put_contents(".htaccess", $lt)) {
if (Log::$a) {
__log("Fuck");
}
echo 'The installer was not able to create a correct ".htaccess" file. Please grant write access on the installation target directory.';
die();
}
@chmod(".htaccess", E2_NEW_FILES_RIGHTS);
}
}
function e2j_check_db_config()
{
global $_db, $_strings, $_config;
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$_POST,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
$dl = [
"success" => true,
"data" => [
"message" => "",
"db-responding" => false,
"db-connected" => false,
"db-found" => false,
"db-compatible" => false,
"db-occupied" => false,
"db-migrateable" => false,
],
];
try {
dm($databaseConfiguration, "connect to check DB config (try 1)");
} catch (AeMySQLAccessDeniedException $e) {
$dl["data"]["db-responding"] = true;
$dl = json_encode($dl);
die($dl);
} catch (AeMySQLCannotConnectException $e) {
$dl = json_encode($dl);
die($dl);
} catch (AeMySQLTooOldException $e) {
$dl["data"]["db-responding"] = true;
$dl["data"]["db-connected"] = true;
$dl["data"]["message"] = e2l_get_string("er--dbs-version-too-old", [
"dbs" => $_db["software"],
"v1" => $_db["version"],
"v2" => $_db["version-minimum"],
]);
$dl = json_encode($dl);
die($dl);
} catch (AeMySQLNotFoundException $e) {
$dl["data"]["db-responding"] = true;
$dl["data"]["db-connected"] = true;
if ($databaseConfiguration->name) {
$dl = json_encode($dl);
die($dl);
} else {
$tt = vm($databaseConfiguration);
if (count($tt) > 0) {
$dl["data"]["db-found"] = true;
$databaseConfiguration->name = $tt[0];
} else {
$dl = json_encode($dl);
die($dl);
}
}
}
$dl["data"]["db-responding"] = true;
$dl["data"]["db-connected"] = true;
$dl["data"]["db-found"] = true;
$dl["data"]["db-compatible"] = true;
try {
dm($databaseConfiguration, "connect to check DB config (try 2)");
} catch (AeMySQLException $e) {
$dl = json_encode($dl);
die($dl);
}
$dl["data"]["db-good"] = true;
$yt = pn($databaseConfiguration);
if ($yt["occupied"]) {
if ($yt["migrateable"]) {
$dl["data"]["message"] = $_strings["gs--data-exists"];
} else {
$dl["data"]["db-good"] = false;
$dl["data"]["message"] =
$_strings["er--db-data-incomplete-install"];
}
}
$dl = json_encode($dl);
die($dl);
}
function e2j_list_databases()
{
global $_config;
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$_POST,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
$jt = [];
$dl = ["success" => true, "data" => ["databases-list" => []]];
try {
$jt = vm($databaseConfiguration);
$dl["data"]["databases-list"] = $jt;
} catch (AeMySQLException $e) {
}
$dl = json_encode($dl);
die($dl);
}
if (substr((string) @$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2) == "ru") {
define("DEFAULT_LANGUAGE", "ru");
} else {
define("DEFAULT_LANGUAGE", "en");
}
function e2l_get_string($ht, $zb)
{
global $_strings;
$name = $_strings[$ht];
if (preg_match_all('/\$\[(.+?)\]/u', $name, $v6, PREG_SET_ORDER)) {
foreach ($v6 as $gt) {
$wt = $gt[1];
$wx = "";
if (strstr($wt, ".")) {
list($wt, $wx) = explode(".", $wt, 2);
}
if (array_key_exists($wt, $zb)) {
if ($wx) {
$name = str_replace(
$gt[0],
e2l__format_value($wx, $zb[$wt], $ht),
$name
);
} else {
$name = str_replace($gt[0], $zb[$wt], $name);
}
}
}
}
return $name;
}
function e2l__format_value($wx, $vv, $ht)
{
@list($wx, $ut) = explode(".", $wx, 2);
$it = "e2lstr_" . $wx;
if (function_exists($it)) {
return call_user_func($it, $vv, $ut, $ht);
} else {
return $vv;
}
return $vv;
}
function fn_()
{
global $_lang, $settings;
if (
array_key_exists("language", $settings) and
is_file(
$ot =
SYSTEM_DIR . LANGUAGES_DIRNAME . $settings["language"] . ".php"
)
) {
$_lang = $settings["language"];
include $ot;
} elseif (
is_file(
$ot = SYSTEM_DIR . LANGUAGES_DIRNAME . DEFAULT_LANGUAGE . ".php"
)
) {
$_lang = DEFAULT_LANGUAGE;
include $ot;
} else {
die("Language file missing: " . $ot);
}
return e2l_load_strings();
}
class Log
{
public static $a = false;
public static $m5 = false;
}
function an()
{
global $_config;
$f5 = INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME;
if (
$_config["write_log"] and
($_config["write_log_create"] or is_file($f5))
) {
Log::$a = true;
Log::$m5 = true;
} else {
Log::$a = false;
Log::$m5 = false;
}
if (!Log::$a) {
return;
}
@nq(INSTANCE_DIR . LOGS_DIRNAME);
if ($_config["write_log_reset"]) {
@file_put_contents($f5, "");
@chmod($f5, E2_NEW_FILES_RIGHTS);
}
if (@$_config["write_log_limit"] and is_file($f5)) {
$cs = @stat($f5);
$cs = $cs["size"];
if ($cs > $_config["write_log_limit"]) {
@rename($f5, $f5 . ".bak");
@chmod($f5 . ".bak", E2_NEW_FILES_RIGHTS);
@file_put_contents($f5, "");
}
}
__log(
""
);
}
function qn($d5 = false)
{
static $s5 = false;
if ($d5 === false) {
return $s5;
}
if ($d5 === "") {
return $s5 = false;
}
$od = str_replace('$', gmdate('Y-m-d-\a\t-H-i-s'), $d5);
return $s5 = $od;
}
function __log($e1)
{
static $q5;
global $_stopwatch;
$l5 = qn();
$f5 = INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME;
if (function_exists("getrusage")) {
$z5 = getrusage();
$k5 = str_pad(
round(
$z5["ru_utime.tv_sec"] + $z5["ru_utime.tv_usec"] / 1000000,
5
),
10,
" ",
STR_PAD_RIGHT
);
} else {
$k5 = str_pad(round(dq() - $_stopwatch, 5), 10, " ", STR_PAD_RIGHT);
}
if ($e1[0] == "}") {
--$q5;
if ($q5 < 0) {
$q5 = 0;
}
}
$x5 = E2_RUN_ID . " " . $k5 . " " . str_repeat(" ", $q5 * 2) . $e1 . "\n";
if ($e1[strlen($e1) - 1] == "{") {
++$q5;
}
$iy = FILE_APPEND;
if (Log::$m5) {
@file_put_contents($f5, $x5, $iy);
@chmod($f5, E2_NEW_FILES_RIGHTS);
}
if ($l5 !== false) {
$od = INSTANCE_DIR . LOGS_DIRNAME . $l5 . ".log";
@nq(INSTANCE_DIR . LOGS_DIRNAME);
@file_put_contents($od, $x5, $iy);
@chmod($l5, E2_NEW_FILES_RIGHTS);
}
if ($e1[0] == "#") {
$e5 = INSTANCE_DIR . LOGS_DIRNAME . "debug.log";
@nq(dirname($e5) . "/");
@file_put_contents($e5, $x5, $iy);
@chmod($e5, E2_NEW_FILES_RIGHTS);
}
}
function ln($r5)
{
@e3(
USER_DIR . "ctree.php",
"<?php\r\n\r\n" . var_export($r5, true) . "\r\n\r\n?>php"
);
}
function zn()
{
$f5 = INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME;
@nq(INSTANCE_DIR . LOGS_DIRNAME);
@file_put_contents($f5, "");
@chmod($f5, E2_NEW_FILES_RIGHTS);
}
define(
"MAIL_ENABLED",
!in_array("mail", explode(",", ini_get("disable_functions")))
);
function kn($t5, $content)
{
$j5 = SYSTEM_DEFAULTS_DIR . "mail/" . $t5 . ".mtmpl.php";
if (is_file($j5)) {
ob_start();
include $j5;
$fa = ob_get_contents();
ob_end_clean();
return trim($fa);
}
}
function xn()
{
global $_config;
$h5 = $_config["mail_from"];
if ($h5[strlen($h5) - 1] == "@") {
$h5 .= $_SERVER["HTTP_HOST"];
}
return $h5;
}
function en($g5, $subject, $zq, $w5 = "")
{
global $_config;
if ($_config["dev_mail_debug"]) {
$w = "mail-debug";
$jv = basename(tempnam($w, "m-"));
$e1 =
"To: " .
$g5 .
"\n" .
"Subject: " .
$subject .
"\n" .
$w5 .
"\n" .
"--------------------------------------------------\n" .
$zq;
e3($w . "/" . $jv, $e1);
chmod($w . "/" . $jv, E2_NEW_FILES_RIGHTS);
rename($w . "/" . $jv, $w . "/" . $jv . ".txt");
}
$subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
$w5 .= "\r\nContent-Type: text/plain; charset=utf-8";
if (MAIL_ENABLED) {
mail($g5, $subject, $zq, trim($w5));
}
}
function rn($parameters, $u5)
{
global $settings;
$i5["each"] = [];
$i5["reorderable?"] = false;
$hd = nf(true, true);
if ($hd === null or $hd === 0) {
return $i5;
}
if (!@$settings["appearance"]["show_main_menu"]) {
return $i5;
}
return $i5;
}
function tn($h2)
{
foreach ($h2 as $vl) {
if ($vl["visible?"]) {
return true;
}
}
return false;
}
function jn()
{
global $settings, $_strings, $_current_url;
$yj = sf();
return [
[
"sort-id" => "f",
"href" => eq("e2m_favourites", ["page" => 1]),
"content-classes" => ["favourites"],
"svg-id" => "favourite-on",
"title" => $_strings["nm--favourites"],
"current?" => AeMainMenuManager::$isFavouritesCurrent,
"parent?" => AeMainMenuManager::$isFavouritesParent,
"visible?" => (bool) @$settings["menu_items"]["favourites_on"],
"available?" => true,
],
[
"sort-id" => "h",
"href" => eq("e2m_most_commented", ["page" => 1]),
"content-classes" => ["most-commented"],
"svg-id" => "comments",
"title" => $_strings["nm--most-commented"],
"current?" => AeMainMenuManager::$isMostCommentedCurrent,
"parent?" => AeMainMenuManager::$isMostCommentedParent,
"visible?" => (bool) @$settings["menu_items"]["most_commented_on"],
"available?" => true,
],
[
"sort-id" => "p",
"href" => eq("e2m_popular", ["page" => 1]),
"content-classes" => ["popular"],
"svg-id" => "read",
"title" => $_strings["nm--most-read"],
"current?" => AeMainMenuManager::$isPopularCurrent,
"parent?" => AeMainMenuManager::$isPopularParent,
"visible?" => (bool) @$settings["menu_items"]["popular_on"],
"available?" => true,
],
[
"sort-id" => "t",
"href" => eq("e2m_tags"),
"svg-id" => "tags",
"title" => $_strings["gs--tags"],
"current?" => AeMainMenuManager::$isTagsCurrent,
"parent?" => AeMainMenuManager::$isTagsParent,
"visible?" => (bool) @$settings["menu_items"]["tags_on"],
"available?" => true,
],
[
"sort-id" => "c",
"href" => p(),
"content-classes" => ["day", "month", "year"],
"svg-id" => "calendar",
"title" => $_strings["gs--calendar"],
"current?" => AeMainMenuManager::$isCalendarCurrent,
"parent?" => AeMainMenuManager::$isCalendarParent,
"visible?" => (bool) @$settings["menu_items"]["calendar_on"],
"available?" => true,
],
[
"sort-id" => "r",
"href" => $yj ? $yj : eq("e2m_frontpage", ["page" => 1]),
"svg-id" => "dice",
"title" => $_strings["nm--random-note"],
"current?" => $_current_url === $yj,
"parent?" => false,
"visible?" =>
$yj !== false and (bool) @$settings["menu_items"]["random_on"],
"available?" => $yj !== false,
],
];
}
function hn($candy, $nj, $mj, $fj, $dj)
{
global $_config, $_template, $_newsfeeds, $_current_url, $_canonical_url;
$meta["base-href"] = AeEnv::$o;
$meta["current-href"] = $_current_url;
$meta["canonical-href"] = $_canonical_url;
$meta["stylesheets"] = y2();
$meta["scripts"] = n2();
$meta["newsfeeds"] = $_newsfeeds;
$meta["favicon-type"] = "image/x-icon";
$meta["favicon-href"] = "favicon.ico";
if ($sj = tv()) {
$meta["favicon-type"] = dd($sj);
$meta["favicon-href"] = $sj;
$meta["apple-touch-icon-href"] = tv("square");
}
$meta["navigation-links"] = [
[
"rel" => "index",
"href" => eq("e2m_frontpage", ["page" => 1]),
"id" => "link-index",
],
];
if (!empty($dj)) {
foreach (["prev", "next", "earlier", "later"] as $aj) {
if (array_key_exists($aj . "-href", $dj)) {
$qj = $aj;
if ($aj == "earlier") {
$qj = "prev";
}
if ($aj == "later") {
$qj = "next";
}
$s1 = $dj[$aj . "-href"];
if ($s1 === "javascript:;") {
continue;
}
$meta["navigation-links"][] = [
"rel" => $qj,
"href" => $s1,
"id" => "link-" . $aj,
];
}
}
}
if (!isset($_template)) {
kf();
}
$meta["viewport"] = $_template["meta_viewport"];
if (is_file($_config["path_media"] . "manifest.json")) {
$meta["manifest-href"] = AeEnv::$o . "manifest.json";
}
$meta["og-images"] = [];
if (is_array($nj["only"]["og-images"])) {
$meta["og-images"] = $nj["only"]["og-images"];
$meta["twitter-card"] = "summary_large_image";
}
if (is_array(@$mj["og-images"])) {
$meta["og-images"] = $mj["og-images"];
$meta["twitter-card"] = "summary_large_image";
}
if (!count($meta["og-images"])) {
$meta["og-images"] = [$fj["userpic-large-href"]];
$meta["twitter-card"] = "summary";
}
return $meta;
}
function gn(AeDatabaseConfiguration $databaseConfiguration)
{
$lj = $databaseConfiguration->getSubset();
if ($lj < 1) {
throw new LogicException(
"Subset to set in place of zero must be greater than 0"
);
}
dm($databaseConfiguration, "prepare migrate db");
am($databaseConfiguration, "SET sql_quote_show_create=1");
}
function wn(AeDatabaseConfiguration $databaseConfiguration)
{
$prefix = $databaseConfiguration->getPrefix();
$lj = $databaseConfiguration->getSubset();
if ($lj < 1) {
throw new LogicException(
"Subset to set in place of zero must be greater than 0"
);
}
dm($databaseConfiguration, "migrate db");
am($databaseConfiguration, "SET sql_quote_show_create=1");
un($databaseConfiguration);
if (Log::$a) {
__log("Fix problems with table structure {");
}
$zj = false;
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
nm($databaseConfiguration, $l2);
am($databaseConfiguration, "SHOW CREATE TABLE `" . $prefix . $l2 . "`");
$kj[$l2] = qm();
$kj[$l2] = $kj[$l2][0]["Create Table"];
am($databaseConfiguration, "SHOW INDEX FROM `" . $prefix . $l2 . "`");
$xj = qm();
$ej = [];
$rj = [];
foreach ($xj as $mb) {
$mb = $mb["Key_name"];
if (
preg_match('/\_[0-9]+$/', $mb) or
$l2 === "Actions" and $mb === "EntityID" or
$l2 === "GIPsSessions" and $mb === "GIP" or
$l2 === "GIPsSessions" and $mb === "SubsetID" or
$l2 === "Notes" and $mb === "Title"
) {
$ej[] = $mb;
$rj[] = "DROP INDEX `" . $mb . "`";
}
if ($l2 === "Actions" and $mb === "EntityID") {
$zj = true;
}
if ($l2 === "Actions" and $mb === "EntityIDStamp") {
$zj = true;
}
}
if (count($rj)) {
$rj = implode(", ", array_unique($rj));
$ej = implode(", ", array_unique($ej));
if (Log::$a) {
__log(
'Drop erroneous index "' .
$ej .
'" on "' .
$prefix .
$l2 .
'"'
);
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . $l2 . "` " . $rj
);
}
if (!strstr($kj[$l2], "InnoDB")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . $l2 . "` " . "ENGINE = InnoDB"
);
}
if (!strstr($kj[$l2], "`SubsetID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
$l2 .
"` " .
"ADD `SubsetID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `ID`"
);
}
if (
$l2 === "Actions" and
strstr($kj["Actions"], "`ReadCount`") and
!$zj
) {
in($databaseConfiguration);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
$l2 .
"` " .
"SET `SubsetID` = " .
$lj .
" " .
"WHERE `SubsetID` = 0"
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Ensure modern table structure {");
}
if (!strstr($kj["Actions"], "`ReadCount`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Actions` " .
"ADD `ReadCount` INT DEFAULT '0' NOT NULL"
);
}
if (strstr($kj["Actions"], "`HitCount`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Actions` " . "DROP `HitCount`"
);
am(
$databaseConfiguration,
"DELETE FROM `" . $prefix . "Actions` " . "WHERE `ReadCount` = 0"
);
}
if (!strstr($kj["Aliases"], "`EntityType`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Aliases` " .
"ADD `EntityType` VARCHAR( 1 ) DEFAULT '' NOT NULL AFTER `ID`"
);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Aliases` " .
"SET `EntityType` = 'n' " .
"WHERE `EntityType` = ''"
);
am(
$databaseConfiguration,
"DELETE FROM `" .
$prefix .
"Aliases` " .
"WHERE `ID` IN (" .
"SELECT `ID` FROM (" .
"SELECT a.`ID` FROM `" .
$prefix .
"Aliases` a " .
"LEFT OUTER JOIN `" .
$prefix .
"Keywords` e " .
"ON a.`EntityID` = e.`ID` " .
"WHERE a.`EntityType` = 't' " .
"AND e.`ID` IS NULL" .
") AS temp" .
")",
"clean up leaked tag aliases"
);
if (!stristr($kj["Comments"], "`Text` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"CHANGE `Text` `Text` MEDIUMTEXT"
);
}
if (!stristr($kj["Comments"], "`Reply` MEDIUMTEXT")) {
if (strstr($kj["Comments"], "`Reply`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"CHANGE `Reply` `Reply` MEDIUMTEXT"
);
} else {
if (Log::$a) {
__log(
"No Reply column in comments; ignored assuming a 2.11 database"
);
}
}
}
if (!stristr($kj["Comments"], "`IP` VARCHAR(39)")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"CHANGE `IP` `IP` VARCHAR(39) DEFAULT '' NOT NULL"
);
}
if (!strstr($kj["Comments"], "`IsGIPUsed`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"ADD `IsGIPUsed` TINYINT(1) DEFAULT '0' NOT NULL AFTER `IP`"
);
}
if (!strstr($kj["Comments"], "`GIP`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"ADD `GIP` VARCHAR(15) DEFAULT '' NOT NULL AFTER `IsGIPUsed`"
);
}
if (!strstr($kj["Comments"], "`GIPAuthorID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"ADD `GIPAuthorID` VARCHAR(64) DEFAULT '' NOT NULL AFTER `GIP`"
);
}
if (strstr($kj["Comments"], "`SocialType`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Comments` " . "DROP `SocialType`"
);
}
if (strstr($kj["Comments"], "`SocialID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Comments` " . "DROP `SocialID`"
);
}
if (!strstr($kj["GIPsSessions"], "`AuthorEmail`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"GIPsSessions` " .
"ADD `AuthorEmail` VARCHAR(255) DEFAULT '' NOT NULL AFTER `AuthorName`"
);
}
if (!strstr($kj["GIPsSessions"], "`AuthorProfileLink`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"GIPsSessions` " .
"ADD `AuthorProfileLink` VARCHAR(255) DEFAULT '' NOT NULL AFTER `AuthorEmail`"
);
}
if (strstr($kj["Keywords"], "`ParentKeywordID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Keywords` " . "DROP `ParentKeywordID`"
);
}
if (!strstr($kj["Keywords"], "`OriginalAlias`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"CHANGE `URLName` `OriginalAlias` VARCHAR( 64 ) DEFAULT '' NOT NULL AFTER `Keyword`"
);
}
if (!strstr($kj["Keywords"], "`PageTitle`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `PageTitle` VARCHAR(255) DEFAULT '' NOT NULL AFTER `OriginalAlias`"
);
}
if (!stristr($kj["Keywords"], "`Description` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"CHANGE `Description` `Description` MEDIUMTEXT"
);
}
if (!strstr($kj["Keywords"], "`Summary`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `Summary` MEDIUMTEXT AFTER `Description`"
);
}
if (!strstr($kj["Keywords"], "`Uploads`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `Uploads` MEDIUMTEXT AFTER `Summary`"
);
}
if (!stristr($kj["Keywords"], "`Uploads` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"CHANGE `Uploads` `Uploads` MEDIUMTEXT"
);
}
if (!strstr($kj["Keywords"], "`IsVisible`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `IsVisible` TINYINT(1) DEFAULT '1' NOT NULL AFTER `Uploads`"
);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Keywords` SET `Summary` = '' WHERE `Summary` IS NULL"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Keywords` SET `Uploads` = '' WHERE `Uploads` IS NULL"
);
if (!strstr($kj["Notes"], "`FormatterID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `FormatterID` VARCHAR( 32 ) DEFAULT '" .
DEFAULT_FORMATTER .
"' NOT NULL AFTER `Text`"
);
}
if (1) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `FormatterID` `FormatterID` VARCHAR( 32 ) DEFAULT '" .
DEFAULT_FORMATTER .
"' NOT NULL"
);
}
if (!strstr($kj["Notes"], "`OriginalAlias`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `URLName` `OriginalAlias` VARCHAR( 64 ) DEFAULT '' NOT NULL AFTER `FormatterID`"
);
}
if (strstr($kj["Notes"], "`IP`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP `IP`"
);
}
if (!stristr($kj["Notes"], "`Text` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `Text` `Text` MEDIUMTEXT"
);
}
if (!strstr($kj["Notes"], "`Summary`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `Summary` MEDIUMTEXT AFTER `Text`"
);
}
if (!strstr($kj["Notes"], "`IsIndexed`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `IsIndexed` TINYINT( 1 ) DEFAULT '0' NOT NULL AFTER `IsDST`"
);
}
if (!strstr($kj["Notes"], "`Uploads`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `Uploads` MEDIUMTEXT AFTER `OriginalAlias`"
);
}
if (!stristr($kj["Notes"], "`Uploads` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `Uploads` `Uploads` MEDIUMTEXT"
);
}
if (!strstr($kj["Notes"], "`IsExternal`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `IsExternal` TINYINT(1) DEFAULT '0' NOT NULL AFTER `IsIndexed`"
);
}
if (!strstr($kj["Notes"], "`SourceID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `IsExternal`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `SourceID`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteURL`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteURL` VARCHAR(255) DEFAULT '' NOT NULL AFTER `SourceNoteID`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteData`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteData` MEDIUMTEXT AFTER `SourceNoteURL`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteJSONURL`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteJSONURL` VARCHAR(255) DEFAULT '' NOT NULL AFTER `SourceNoteData`"
);
}
if (strstr($kj["Notes"], "`SourceMainImageURL`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP `SourceMainImageURL`"
);
}
if (strstr($kj["Notes"], "`IsIssue`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP `IsIssue`"
);
}
if (!strstr($kj["Notes"], "`ReadCount`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `ReadCount` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `IsExternal`"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` n JOIN (" .
"SELECT `EntityID`, SUM(`ReadCount`) `AggregateReadCount` " .
"FROM `" .
$prefix .
"Actions` " .
"GROUP BY `EntityID`" .
") a ON n.`ID` = a.`EntityID` " .
"SET `ReadCount` = `AggregateReadCount`"
);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` SET `Summary` = '' WHERE `Summary` IS NULL"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` SET `Uploads` = '' WHERE `Uploads` IS NULL"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` SET `SourceNoteData` = '' WHERE `SourceNoteData` IS NULL"
);
if (!strstr($kj["Sources"], "`TrueID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Sources` " .
"ADD `TrueID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `ID`"
);
am(
$databaseConfiguration,
"UPDATE `" . $prefix . "Sources` " . "SET `TrueID` = `ID`"
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Ensure indexes {");
}
if (strstr($kj["Notes"], "`Title` (`Title`(191))")) {
if (Log::$a) {
__log('Drop erroneous index on "' . $prefix . 'Notes.Title"');
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP INDEX `Title`"
);
}
on($databaseConfiguration);
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
foreach (AeModel::indexesByUnprefixedTableName($l2) as $mb) {
list($type, $fb) = $mb;
$db = implode("", $fb);
$tj =
AeModel::indexCheckSQLByIndexType($type) .
" `" .
$db .
"` (`" .
implode("`,`", $fb) .
"`)";
$sb =
AeModel::indexCreateSQLByIndexType($type) .
" `" .
$db .
"` (`" .
implode("`, `", $fb) .
"`)";
if (!strstr($kj[$l2], $tj)) {
if (Log::$a) {
__log(
'Table "' .
$prefix .
$l2 .
'" is missing "' .
AeModel::indexCheckSQLByIndexType($type) .
'" on columns "' .
implode('", "', $fb) .
'"'
);
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . $l2 . "` " . "ADD " . $sb
);
}
}
}
if (Log::$a) {
__log("}");
}
return true;
}
function un(AeDatabaseConfiguration $databaseConfiguration)
{
if (Log::$a) {
__log("Ensure encoding utf8mb4 on all native tables {");
}
foreach (AeModel::unprefixedCoreTablesNames() as $jj) {
$hj = $databaseConfiguration->getPrefix() . $jj;
if (Log::$a) {
__log("Migrate: Check table " . $hj);
}
$gj = ym($databaseConfiguration, $jj);
if (!$gj) {
continue;
}
if (stripos($gj["Collation"], "utf8mb4") === 0) {
continue;
}
if (Log::$a) {
__log("Migrate: Table " . $hj . " has a wrong encoding");
}
if (Log::$a) {
__log("Migrate: Drop indexes of table " . $hj);
}
am(
$databaseConfiguration,
"SHOW INDEX FROM `" .
$hj .
"` " .
"WHERE `Key_name` <> 'PRIMARY' " .
"AND `Seq_in_index` = 1",
"show indexes from table " . $hj
);
$xj = qm();
foreach ($xj as $mb) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$hj .
"` " .
"DROP INDEX `" .
$mb["Key_name"] .
"`",
"drop index " . $mb["Key_name"]
);
}
if (Log::$a) {
__log("Migrate: Convert table " . $hj . " to utf8mb4");
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $hj . "` " . "CONVERT TO CHARACTER SET utf8mb4",
"convert table to character set utf8mb4"
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Ensure encoding utf8mb4 on all Rose tables {");
}
foreach (td() as $wj) {
$hj = $databaseConfiguration->getPrefix() . SEARCH_EXTRA_PREFIX . $wj;
if (Log::$a) {
__log("Migrate: Check table " . $hj);
}
$gj = ym($databaseConfiguration, SEARCH_EXTRA_PREFIX . $wj);
if (!$gj) {
continue;
}
if (stripos($gj["Collation"], "utf8mb4") === 0) {
continue;
}
if (Log::$a) {
__log(
"Some Rose tables have a wrong encoding, will need to erase and recreate them all"
);
}
wd($databaseConfiguration);
break;
}
if (Log::$a) {
__log("}");
}
}
function in(AeDatabaseConfiguration $databaseConfiguration)
{
$prefix = $databaseConfiguration->getPrefix();
if (Log::$a) {
__log(
'Table "' .
$prefix .
'Actions" is missing necessary UNIQUE index, must rearrange {'
);
}
am(
$databaseConfiguration,
"DROP TABLE IF EXISTS `" . $prefix . "Actions_Fixed`",
"remove temporary Actions_Fixed table if exists"
);
am(
$databaseConfiguration,
"CREATE TABLE `" .
$prefix .
"Actions_Fixed` " .
"LIKE `" .
$prefix .
"Actions`",
"create new temporary Actions_Fixed table"
);
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Actions_Fixed` " .
"ADD UNIQUE INDEX(`EntityID`, `Stamp`)",
"add UNIQUE index to the temporary Actions_Fixed table"
);
am(
$databaseConfiguration,
"INSERT INTO `" .
$prefix .
"Actions_Fixed` (`SubsetID`, `EntityID`, `Stamp`, `ReadCount`) " .
"SELECT `SubsetID`, `EntityID`, `Stamp`, `AggregateReadCount` FROM (" .
"SELECT `SubsetID`, `EntityID`, `Stamp`, SUM(`ReadCount`) `AggregateReadCount` " .
"FROM `" .
$prefix .
"Actions` " .
"GROUP BY `EntityID`, `Stamp`" .
") `" .
$prefix .
"Actions_Fixed_AliasRequiredForNoReason`",
"rearrange Actions records from existing problematic Actions table to the new temporary Actions_Fixed table"
);
am(
$databaseConfiguration,
"RENAME TABLE `" .
$prefix .
"Actions` TO `" .
$prefix .
"Actions_Corrupt`",
"rename Actions to Actions_Corrupt"
);
am(
$databaseConfiguration,
"RENAME TABLE `" .
$prefix .
"Actions_Fixed` TO `" .
$prefix .
"Actions`",
"rename Actions_Fixed to Actions"
);
am(
$databaseConfiguration,
"DROP TABLE `" . $prefix . "Actions_Corrupt`",
"remove Actions_Corrupt table"
);
if (Log::$a) {
__log("}");
}
}
function on($databaseConfiguration)
{
global $_db;
$uj =
"(0 " .
"OR `Text` LIKE '%!!%' " .
"OR `Text` LIKE '%||%' " .
"OR `Text` LIKE '%\%\%%' " .
"OR `Text` LIKE '%##%' " .
"OR `Text` LIKE '%++%' " .
"OR `Text` LIKE '%((html%' " .
"OR `Text` LIKE '%((img%' " .
"OR `Text` LIKE '%((link%' " .
"OR `Text` LIKE '%((%.jpg%' " .
"OR `Text` LIKE '%((%.jpeg%' " .
"OR `Text` LIKE '%((%.gif%' " .
"OR `Text` LIKE '%((%.png%' " .
"OR `Text` LIKE '%((%.webp%' " .
"OR `Text` LIKE '%[[html%' " .
"OR `Text` LIKE '%[[img%' " .
"OR `Text` LIKE '%[[link%' " .
"OR `Text` LIKE '%[[%.jpg%' " .
"OR `Text` LIKE '%[[%.jpeg%' " .
"OR `Text` LIKE '%[[%.gif%' " .
"OR `Text` LIKE '%[[%.png%' " .
"OR `Text` LIKE '%[[%.webp%' " .
")";
if (Log::$a) {
__log("Switch from Calliope to Neasden {");
}
am(
$databaseConfiguration,
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"SET `FormatterID` = 'neasden' " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `FormatterID` = 'calliope' " .
"AND (" .
"`IsPublished` = '0' " .
"OR (" .
"`IsPublished` = '1' " .
"AND !" .
$uj .
")" .
")"
);
if (Log::$a) {
__log(
mysqli_affected_rows($_db["link"]) .
" drafts and notes with simple formatting switched"
);
}
am(
$databaseConfiguration,
"SELECT `ID` FROM `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `FormatterID` = 'calliope'"
);
$ff = qm();
if (Log::$a) {
__log(count($ff) . " with complex formatting remain");
}
if (count($ff) > 0) {
$gv = "AEGEA-LEGACY-REVIEW";
$ij = aa($databaseConfiguration, $gv);
if (!$ij) {
$ij["ID"] = fa($databaseConfiguration, $gv, false);
}
if (Log::$a) {
__log('Tag "' . $gv . '" has ID ' . $ij["ID"]);
}
foreach ($ff as $zy) {
sm(
"INSERT INTO `" .
$databaseConfiguration->getPrefix() .
"NotesKeywords` " .
"(`SubsetID`, `NoteID`, `KeywordID`) " .
"VALUES (" .
((int) $databaseConfiguration->getSubset()) .
", " .
((int) $zy["ID"]) .
", " .
((int) $ij["ID"]) .
")",
"add new tag bindings"
);
}
$il = "Aegea legacy notes for review";
$bq =
"These notes were automatically converted from a very old version of Aegea and may have formatting problems. Please edit them to fix these problems. When finished, just delete this tag.";
am(
$databaseConfiguration,
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Keywords` " .
"SET `IsVisible` = 0, `IsFavourite` = 1, " .
"`PageTitle` = '" .
$il .
"', " .
"`Description` = '" .
$bq .
"' " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `ID` = " .
$ij["ID"]
);
am(
$databaseConfiguration,
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"SET `FormatterID` = 'neasden' " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `FormatterID` = 'calliope'"
);
if (Log::$a) {
__log(
"Switched " .
mysqli_affected_rows($_db["link"]) .
" notes with complex formatting"
);
}
}
if (Log::$a) {
__log("}");
}
}
function pn(AeDatabaseConfiguration $databaseConfiguration)
{
global $_db;
$oj = false;
$pj = [];
$sql =
"SHOW TABLES FROM `" .
mysqli_real_escape_string($_db["link"], $databaseConfiguration->name) .
"`";
if (Log::$a) {
__log("DB [?]: " . $sql);
}
$h3 = mysqli_query($_db["link"], $sql);
if ($h3) {
while ($j2 = mysqli_fetch_row($h3)) {
foreach (AeModel::unprefixedCoreTablesNames() as $jj) {
if (
strcasecmp(
$j2[0],
$databaseConfiguration->getPrefix() . $jj
) === 0
) {
$oj = true;
$pj[] = $jj;
}
}
}
}
$ch = true;
foreach (AeModel::unprefixedCoreTablesNames() as $jj) {
if (!in_array($jj, $pj)) {
$ch = false;
}
}
$vh = true;
foreach (AeModel::unprefixedEssentialTablesNames() as $jj) {
if (!in_array($jj, $pj)) {
$vh = false;
}
}
return ["occupied" => $oj, "complete" => $ch, "migrateable" => $vh];
}
function cm($databaseConfiguration)
{
dm($databaseConfiguration);
$yt = pn($databaseConfiguration);
if (!$yt["occupied"]) {
throw new AeMySQLNoDataException("Database is empty");
}
if (!$yt["migrateable"]) {
throw new AeMySQLNotMigrateableException("Database is not migrateable");
}
}
function vm(AeDatabaseConfiguration $databaseConfiguration)
{
global $vs;
if (
($ix = mysqli_connect(
"p:" . $databaseConfiguration->host,
$databaseConfiguration->user,
ks($databaseConfiguration->password),
"",
$databaseConfiguration->port
)) === false
) {
return [];
}
$tt = [];
$bh = ["information_schema", "performance_schema", "sys", "mysql"];
@$vs++;
$e2_ = "SHOW DATABASES";
if (Log::$a) {
__log("DB [" . $vs . "]: " . $e2_);
}
$h3 = mysqli_query($ix, $e2_);
if ($h3 === false) {
throw new AeMySQLQueryException(
"Could not list databases\n\nMySQL says:\n" . mysqli_error($ix)
);
}
while ($j2 = mysqli_fetch_row($h3)) {
if (mysqli_select_db($ix, $j2[0]) and !in_array($j2[0], $bh)) {
$tt[] = $j2[0];
}
}
return $tt;
}
function bm($databaseConfiguration, $l2)
{
am(
$databaseConfiguration,
"SHOW TABLES LIKE '" . $databaseConfiguration->getPrefix() . $l2 . "'"
);
$dr = qm();
return count($dr) > 0;
}
function ym($databaseConfiguration, $l2)
{
am(
$databaseConfiguration,
"SHOW TABLE STATUS LIKE '" .
$databaseConfiguration->getPrefix() .
$l2 .
"'"
);
$h3 = qm();
return $h3 ? $h3[0] : [];
}
function nm($databaseConfiguration, $l2)
{
if (bm($databaseConfiguration, $l2)) {
return;
}
am(
$databaseConfiguration,
"CREATE TABLE `" .
$databaseConfiguration->getPrefix() .
$l2 .
"` " .
AeModel::columnsAndIndexesSQLByUnprefixedTableName($l2) .
" " .
"ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
);
}
function mm(
AeDatabaseConfiguration $databaseConfiguration,
$l2,
$u4,
$oz = "INSERT",
$yh = ""
) {
global $_db;
$nh["SubsetID"] = $databaseConfiguration->getSubset();
foreach ($u4 as $k3 => $x3) {
$nh[$k3] = "'" . lm($x3) . "'";
}
$mh = "`" . implode("`, `", array_keys($nh)) . "`";
$fh = implode(", ", array_values($nh));
am(
$databaseConfiguration,
$oz .
" INTO `" .
$databaseConfiguration->getPrefix() .
$l2 .
"` " .
"(" .
$mh .
") VALUES (" .
$fh .
")" .
($yh ? " " . $yh : "")
);
$u4["ID"] = mysqli_insert_id($_db["link"]);
return $u4;
}
function fm(
AeDatabaseConfiguration $databaseConfiguration,
$l2,
$u4,
$dh = false,
$sh = false
) {
if (Log::$a) {
__log("Model: update record in table " . $l2 . " {");
}
$ah = [];
foreach (AeModel::softFieldsByUnprefixedTableName($l2) as $x) {
if (array_key_exists($x, $u4)) {
$ah[] = "`" . $x . "`" . "='" . lm($u4[$x]) . "'";
}
}
$qh = [];
if (is_array($dh)) {
foreach (AeModel::softFieldsByUnprefixedTableName($l2) as $x) {
if (array_key_exists($x, $dh)) {
$qh[] = "`" . $x . "`" . "='" . lm($dh[$x]) . "'";
}
}
}
if (count($qh)) {
$m1 = implode(" AND ", $qh);
} else {
if (!array_key_exists("ID", $u4) or !is_numeric($u4["ID"])) {
if (Log::$a) {
__log(
'Error: e2_update_record must be called with an ID field in $record when updating single row'
);
}
return false;
}
$m1 = "`ID`=" . $u4["ID"];
}
if (count($ah) > 0) {
$lh = $sh ? "LOW_PRIORITY " : "";
am(
$databaseConfiguration,
"UPDATE " .
$lh .
"`" .
$databaseConfiguration->getPrefix() .
$l2 .
"` " .
"SET " .
implode(", ", $ah) .
" " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND (" .
$m1 .
")"
);
}
if (Log::$a) {
__log("}");
}
return true;
}
define("E2_MYSQL_CONNECT_TIMEOUT", 5);
function dm(AeDatabaseConfiguration $databaseConfiguration, $zh = "")
{
static $kh = false;
static $xh = false;
global $_instance_config, $_db, $vs;
if ($kh !== $databaseConfiguration->getServerKeyString()) {
if (Log::$a) {
__log(
'Ensure: Establishing connection "' .
$databaseConfiguration->getServerKeyString() .
'"'
);
}
if ($kh !== false) {
if (Log::$a) {
__log("Closing previous database connection");
}
mysqli_close($_db["link"]);
}
$eh = mysqli_init();
$eh->options(MYSQLI_OPT_CONNECT_TIMEOUT, E2_MYSQL_CONNECT_TIMEOUT);
if (
$_instance_config["dev_chaos"] and
!rand(0, 1 / $_instance_config["dev_chaos"] - 1)
) {
throw new AeMySQLCannotConnectException(
"Could not " . $zh . "\n\nChaos"
);
}
$rh = @mysqli_real_connect(
$eh,
"p:" . $databaseConfiguration->host,
$databaseConfiguration->user,
ks($databaseConfiguration->password),
"",
$databaseConfiguration->port
);
if (!$rh) {
$y2 = mysqli_connect_errno();
if (1045 === $y2) {
throw new AeMySQLAccessDeniedException(
"Could not " . $zh . " (" . $y2 . ")"
);
} else {
throw new AeMySQLCannotConnectException(
"Could not " . $zh . " (" . $y2 . ")"
);
}
}
if (!xm($eh)) {
throw new AeMySQLTooOldException("Could not " . $zh);
}
$_db["link"] = $eh;
$kh = $databaseConfiguration->getServerKeyString();
$xh = false;
}
if ($xh !== $databaseConfiguration->name) {
if (Log::$a) {
__log(
'Ensure: Selecting database "' .
$databaseConfiguration->name .
'"'
);
}
if (!@mysqli_select_db($_db["link"], $databaseConfiguration->name)) {
throw new AeMySQLNotFoundException("Could not " . $zh);
}
$e2_ = "SET NAMES utf8mb4";
mysqli_query($_db["link"], $e2_);
@$vs++;
if (Log::$a) {
__log("DB [" . $vs . "]: " . $e2_);
}
$xh = $databaseConfiguration->name;
}
}
function sm($e2_, $zh = "run some query")
{
$databaseConfiguration = bl();
return am($databaseConfiguration, $e2_, $zh);
}
function am($databaseConfiguration, $e2_, $zh = "")
{
global $vs, $_db, $_config;
dm($databaseConfiguration, $zh);
if ($_config["dev_chaos"] and !rand(0, 1 / $_config["dev_chaos"] - 1)) {
throw new AeMySQLQueryException(
"Could not " . $zh . "\n\nChaos in e2_mysql_query"
);
}
@$vs++;
if (Log::$a) {
if ($zh) {
__log("Will " . $zh);
}
}
if (Log::$a) {
__log("DB [" . $vs . "]: " . $e2_);
}
$_db["result"] = @mysqli_query($_db["link"], $e2_);
if ($_db["result"]) {
if ($_config["backup_tail"]) {
if (stripos($e2_, "SELECT") !== 0 and stripos($e2_, "SHOW") !== 0) {
$od = $databaseConfiguration->backup_dir . "backup-tail.sql";
@file_put_contents(
$od,
$e2_ . ";\r\n\r\n",
FILE_APPEND | LOCK_EX
);
@chmod($od, E2_NEW_FILES_RIGHTS);
}
}
} else {
throw new AeMySQLQueryException(
"Could not " .
$zh .
"\n\nMySQL says:\n" .
mysqli_error($_db["link"])
);
}
}
function qm($type = MYSQLI_ASSOC)
{
global $_db;
$vb = [];
while ($p5 = @mysqli_fetch_array($_db["result"], $type)) {
foreach ($p5 as $gb => $th) {
if (is_string($th)) {
$p5[$gb] = $th;
}
}
$vb[] = $p5;
}
return $vb;
}
function lm($m4)
{
global $_db;
dm(bl(), "escape string");
return mysqli_real_escape_string($_db["link"], (string) $m4);
}
function zm()
{
global $_config;
$tv = array_keys(km(USER_DIR . BACKUP_DIRNAME));
if (Log::$a) {
__log("Backup: Found " . count($tv) . " backups");
}
if (count($tv)) {
$jh = time() - $tv[0];
$hh = $jh >= $_config["backup_rebase_interval"];
if (Log::$a) {
__log("Backup: " . $jh . " seconds since last backup");
}
} else {
$hh = true;
}
if ($hh) {
if (Log::$a) {
__log("Backup: Will rebuild backup");
}
vv(eq("e2s_dump", []), true);
}
}
function km($backup_dir)
{
$tv = [];
foreach (glob($backup_dir . "*.sql") as $s2) {
if (
preg_match(
'/^backup\-(\d+)\-(\d+)\-(\d+)\-at\-(\d+)\-(\d+)\-(\d+)\.sql$/is',
basename($s2),
$v6
)
) {
list(, $gm, $wm, $um, $gh, $gb, $wh) = $v6;
$mf = gmmktime(
(int) $gh,
(int) $gb,
(int) $wh,
(int) $wm,
(int) $um,
(int) $gm
);
$tv[$mf] = $s2;
}
}
krsort($tv);
return $tv;
}
function xm($eh)
{
global $_db;
$_db["software"] = "MySQL";
$_db["version-minimum"] = E2_MINIMUM_MYSQL;
$_db["version"] = mysqli_get_server_info($eh);
$ih = strpos($_db["version"], "-MariaDB");
if ($ih !== false) {
$_db["software"] = "MariaDB";
$_db["version-minimum"] = E2_MINIMUM_MARIADB;
$_db["version"] = substr($_db["version"], 0, $ih);
if (substr($_db["version"], 0, 6) === "5.5.5-") {
$_db["version"] = substr($_db["version"], 6);
}
}
if (Log::$a) {
__log(
'Ensure: Running on "' .
$_db["software"] .
'", version "' .
$_db["version"] .
'"'
);
}
return version_compare($_db["version"], $_db["version-minimum"], ">=");
}
function em($backup_dir)
{
$tv = km($backup_dir);
$oh = [
SECONDS_IN_A_MINUTE,
SECONDS_IN_AN_HOUR,
SECONDS_IN_A_DAY,
SECONDS_IN_A_WEEK,
SECONDS_IN_A_MONTH,
-1,
];
$ph = count($tv);
$c8 = count($oh) - 1;
if ($ph > $c8) {
if (Log::$a) {
__log(
"Stored are " . $ph . " backups, over " . $c8 . ", will sift..."
);
}
$v8 = -1;
$gb = 0;
foreach ($tv as $mf => $s2) {
if (Log::$a) {
__log("Backup " . $s2 . " (" . gmdate("r", $mf) . ")");
}
if ($v8 == -1) {
if (Log::$a) {
__log("is latest, leave");
}
$v8 = $mf;
} elseif ($oh[$gb] == -1) {
if (Log::$a) {
__log("is too old, remove");
}
@unlink($s2);
} else {
if ($v8 - $mf < $oh[$gb]) {
if (Log::$a) {
__log(
"is not from long ago (within interval of " .
$oh[$gb] .
"s), remove"
);
}
@unlink($s2);
} else {
$gb++;
if (Log::$a) {
__log(
"is long enough ago, leave (proceed to interval of " .
$oh[$gb] .
"s)"
);
}
$v8 = $mf;
}
}
}
} else {
if (Log::$a) {
__log("No need to sift");
}
}
return;
}
function rm(AeDatabaseConfiguration $databaseConfiguration)
{
global $_db;
if (Log::$a) {
__log("Backup to " . $databaseConfiguration->backup_dir);
}
dm($databaseConfiguration, "make backup");
$nd = [];
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
$nd[] = $databaseConfiguration->getPrefix() . $l2;
}
$l = time();
$od =
$databaseConfiguration->backup_dir .
"backup-" .
gmdate('Y-m-d-\a\t-H-i-s', $l) .
".sql";
if ($databaseConfiguration->hasSubsetSpecified()) {
$subset = $databaseConfiguration->getSubset();
} else {
$subset = null;
}
e2_backup($_db["link"], $nd, $subset, $od);
@unlink($databaseConfiguration->backup_dir . "backup-tail.sql");
em($databaseConfiguration->backup_dir);
return $od;
}
function tm($b8)
{
$y8 = parse_url($b8);
$n8 = @$y8["host"];
$m8 = @$y8["port"];
if ((string) $n8 === "") {
$n8 = $b8;
$m8 = "";
}
return [$n8, $m8];
}
function e2s_dump()
{
global $_config;
if (!$_config["allow_underhood_access"]) {
z1(eq("e2m_settings"));
}
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_underhood"));
}
if (rm(bl())) {
hb("Backed up", E2E_MESSAGE);
}
z1(eq("e2m_underhood"));
}
function e2m_note($parameters = [])
{
global $settings, $_config, $_strings;
if (Log::$a) {
__log("Note {");
}
$zy = @$parameters["*note"];
if ($zy == false) {
return e2m_error404();
}
$f8 = af($zy);
$sf = ff($zy);
$gn = ys();
$d8 = $parameters["preview-key"] == $f8;
if (!empty($parameters["preview-key"]) and !$d8) {
return e2m_error404();
}
if (!$gn and !$d8 and $sf !== "public") {
return e2m_error404();
}
if (!empty($parameters["preview-key"]) and $sf === "public") {
unset($parameters["preview-key"]);
$na = eq("e2m_note", $parameters);
z1($na);
}
$na = eq("e2m_note", $parameters);
$noteView = new AeNoteView($zy);
$noteView->setWantReadHref($_config["count_reads"]);
$noteView->setWantControls($gn and !@$_config["read_only"]);
$noteView->setWantHiddenTags($gn);
if ($sf === "draft" or $sf === "scheduled") {
if (!$d8) {
$s8 = [
".note-id" => $zy["ID"],
"form-action" => eq("e2s_note_publish"),
"submit-text" => $_strings["fb--publish-note"],
"can-schedule?" => false,
"can-publish?" => !@$_config["read_only"],
"scheduling-promo" => e2l_get_string("pm--scheduling", [
"url" => $_config["paid_features_url"],
]),
];
}
}
$a8 = "";
$q8 = [];
$dj = [];
if ($sf === "public") {
$noteView->setWantNewCommentsCount($gn);
$noteView->setWantSharingButtons(
@$settings["appearance"]["show_sharing_buttons"]
);
$noteView->setWantRelatedNotes(true);
}
if ($sf === "public" or $sf === "hidden") {
if (Log::$a) {
__log("Navigation {");
}
$l8 = um($zy, "prev");
$z8 = um($zy, "next");
if ($l8) {
$dj["prev-href"] = eq("e2m_note", ["*note" => $l8]);
$dj["prev-title"] = ay(
htmlspecialchars($l8["Title"], ENT_NOQUOTES, "UTF-8")
);
}
if ($z8) {
$dj["next-href"] = eq("e2m_note", ["*note" => $z8]);
$dj["next-title"] = ay(
htmlspecialchars($z8["Title"], ENT_NOQUOTES, "UTF-8")
);
}
$dj["title"] = $_strings["nm--posts"];
$dj["timeline?"] = false;
$dj["this-title"] = ay(
htmlspecialchars($zy["Title"], ENT_NOQUOTES, "UTF-8")
);
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Comments {");
}
if ($gn) {
$k8 = e2_note_cache_filename_with_id_(
$zy["ID"] . "-comments-author"
);
} else {
$k8 = e2_note_cache_filename_with_id_($zy["ID"] . "-comments");
}
$x8 = null;
if (CACHE_NOTES_COMMENTS and is_file($k8)) {
$x8 = @unserialize(file_get_contents($k8));
}
if (is_array($x8)) {
if (Log::$a) {
__log("retrieve cached ctree");
}
$a8 = $x8;
} else {
if (Log::$a) {
__log("assemble ctree...");
}
$e8 = zb($zy["ID"]);
$x1 = [];
$r8 = true;
foreach ($e8 as $k3 => $ls) {
if ($ls["IsVisible"]) {
$gs = mb($zy, $ls, $k3 + 1);
if ($gs["new?"] and $r8) {
$gs["first-new?"] = true;
$r8 = false;
}
$x1[] = $gs;
}
}
$a8 = $x1;
if (CACHE_NOTES_COMMENTS) {
e3($k8, serialize($a8));
}
}
if ($t8 = db($zy)) {
$t8[".comment-number"] = count($a8) + 1;
}
if (Log::$a) {
__log("} // Comments");
}
}
$u3 = $noteView->getNoteCTree();
if ($gn and xb($zy, NOTE_COMMENTABLE_NOW_CONDITIONALLY)) {
$q8["form-action"] = eq("e2s_note_flag", [
"*note" => $zy,
"flag" => "IsCommentable",
"value" => (int) !$zy["IsCommentable"],
]);
$q8["submit-text"] = $zy["IsCommentable"]
? $_strings["bt--close-comments-to-post"]
: $_strings["bt--open-comments-to-post"];
}
if ($gn and $u3["new-comments-count"] > 0) {
if (Log::$a) {
__log("mark comments as not new");
}
e2_drop_caches_for_note_($zy["ID"], true);
fm(bl(), "Comments", ["IsNew" => 0], ["NoteID" => $zy["ID"]]);
}
if (CACHE_RANDOM_NOTE and is_file(USER_DIR . CACHE_FILENAME_RANDOM_NOTE)) {
$yj = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_RANDOM_NOTE)
);
if (((string) $yj) === $u3["href"]) {
@unlink(USER_DIR . CACHE_FILENAME_RANDOM_NOTE);
}
}
foreach ($u3["tags"] as $gv) {
AeMainMenuManager::addParentTag($gv["name"]);
}
$vb = [
"title" => $zy["Title"],
"notes" => ["only" => $u3],
"pages" => $dj,
"summary" => $u3["summary"],
];
if ($a8) {
$vb["comments"]["each"] = $a8;
}
if ($q8) {
$vb["comments"]["toggle"] = $q8;
}
$vb["comments"]["count"] = $u3["comments-count"];
$vb["comments"]["count-text"] = $u3["comments-count-text"];
$vb["comments"]["new-count"] = $u3["new-comments-count"];
$vb["comments"]["new-count-text"] = $u3["new-comments-count-text"];
$vb["comments"]["display-form?"] = xb($zy);
if (!empty($t8)) {
$vb["form"] = "form-comment";
$vb["form-comment"] = $t8;
}
if (!empty($s8)) {
$vb["form"] = "form-note-publish";
$vb["form-note-publish"] = $s8;
}
if (Log::$a) {
__log("} // Note");
}
return $vb;
}
function e2m_note_read($parameters = [])
{
global $_config;
if (!$_config["count_reads"]) {
die("Read counting disabled");
}
$zy = $parameters["*note"];
if ($zy == false) {
return e2m_error404();
}
if (Log::$a) {
__log("Note read {");
}
sm(
"UPDATE LOW_PRIORITY `" .
$_config["db_table_prefix"] .
"Notes` " .
"SET `ReadCount` = `ReadCount` + 1 " .
"WHERE `ID` = " .
$zy["ID"]
);
$j8 = time();
$j8 = $j8 - ($j8 % SECONDS_IN_AN_HOUR);
mm(
bl(),
"Actions",
["EntityID" => $zy["ID"], "Stamp" => $j8, "ReadCount" => 1],
"INSERT LOW_PRIORITY",
"ON DUPLICATE KEY UPDATE `ReadCount` = `ReadCount` + 1"
);
sm(
"DELETE LOW_PRIORITY FROM `" .
$_config["db_table_prefix"] .
"Actions` " .
"WHERE (`Stamp` < " .
(time() - SECONDS_IN_A_MONTH) .
")"
);
if (Log::$a) {
__log("}");
}
z1(eq("e2m_note", $parameters));
}
function e2m_note_withdraw($parameters = [])
{
$databaseConfiguration = bl();
$s = $parameters["*note"];
if (!$s) {
return e2m_error404();
}
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_note", ["*note" => $s]));
}
od();
$h8 = eq("e2m_note_broadcast", ["*note" => $s]);
$s["IsPublished"] = 0;
$s["IsCommentable"] = 0;
$s["IsVisible"] = 1;
$s["Stamp"] = time();
$s["IP"] = pd();
$ry = e2_alias_of_note_with_id_($s["ID"]);
if ($ry) {
$s["OriginalAlias"] = $ry;
} else {
$s["OriginalAlias"] = d(
USER_DIR,
$databaseConfiguration,
"find",
"n",
$s["ID"],
$s["Title"]
);
}
e2_drop_caches_for_note_($s["ID"], null);
fm($databaseConfiguration, "Notes", $s);
e2_delete_aliases_for_entity_("n", $s["ID"]);
ed($s["ID"]);
vv($h8);
z1(eq("e2m_note", ["*note" => $s]));
}
function e2m_note_delete($parameters = [])
{
global $_strings;
$s = @$parameters["*note"];
if (!$s) {
return e2m_error404();
}
$sf = ff($s);
$g8 = !$s["IsPublished"];
if ($g8) {
$w8 = e2l_get_string("gs--draft-will-be-deleted", [
"draft" => htmlspecialchars($s["Title"], ENT_NOQUOTES, "UTF-8"),
]);
} else {
$w8 = e2l_get_string("gs--post-will-be-deleted", [
"post" => htmlspecialchars($s["Title"], ENT_NOQUOTES, "UTF-8"),
]);
}
$ss = $g8
? $_strings["pt--draft-deletion"]
: $_strings["pt--post-deletion"];
$u8 = [
".note-id" => $s["ID"],
".is-draft" => (int) $g8,
"note-title" => htmlspecialchars($s["Title"], ENT_COMPAT, "UTF-8"),
"caution-text" => $w8,
"form-action" => eq("e2s_note_delete"),
"submit-text" => $_strings["fb--delete"],
"draft?" => (int) $g8,
];
if ($sf === "public") {
$u8["hide-action"] = eq("e2s_note_flag", [
"*note" => $parameters["*note"],
"flag" => "IsVisible",
"value" => 0,
]);
}
if ($s["IsPublished"]) {
$u8["withdraw-action"] = eq("e2m_note_withdraw", $parameters);
}
$vb = [
"title" =>
$ss . ": " . htmlspecialchars($s["Title"], ENT_NOQUOTES, "UTF-8"),
"heading" => $ss,
"form" => "form-note-delete",
"form-note-delete" => $u8,
];
return $vb;
}
function e2s_note_flag_favourite($parameters)
{
$parameters["flag"] = "IsFavourite";
g1([
"flag-name" => "favourite",
"candy-name" => "e2s_note_flag_favourite",
"parameters" => $parameters,
"flipping-function" => function () use ($parameters) {
jm($parameters);
},
"redirect-candy" => "e2m_note",
]);
}
function e2s_note_flag($parameters)
{
jm($parameters);
z1(eq("e2m_note", $parameters));
}
function jm($parameters)
{
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_note", $parameters));
}
od();
$note_id = $parameters["*note"]["ID"];
if (!is_numeric($note_id)) {
throw new AeException("Note record not cound from parameters");
}
e2_drop_caches_for_note_($note_id, $parameters["*note"]["IsPublished"]);
if ($parameters["flag"] == "IsVisible") {
cb();
}
fm(bl(), "Notes", [
"ID" => $note_id,
$parameters["flag"] => (int) ($parameters["value"] == 1),
]);
try {
hv(wm($note_id));
} catch (AeMySQLException $e) {
v3($e, "Could not broadcast note flag change");
}
return true;
}
function e2m_note_use_formatter($parameters)
{
$note_id = $parameters["*note"]["ID"];
if (!is_numeric($note_id)) {
return e2m_error404();
}
e2_drop_caches_for_note_($note_id, $parameters["*note"]["IsPublished"]);
if (in_array($parameters["formatter"], ["raw", "neasden"])) {
fm(bl(), "Notes", [
"ID" => $note_id,
"FormatterID" => $parameters["formatter"],
]);
echo "formatter set to " . $parameters["formatter"];
} else {
echo "unknown formatter";
}
die();
}
function hm($ds, $parameters = [])
{
global $_strings;
$ss = $_strings["pt--new-post"];
$as_ = $_strings["pt--new-post"];
$note_id = "new";
$i8 = DEFAULT_FORMATTER;
if ($ds == "write") {
$mf = time();
$o8 = time();
$ob = pa();
$sf = "draft";
$ry = $p8 = "";
}
if ($ds == "edit") {
$s = @$parameters["*note"];
if (!$s) {
return e2m_error404();
}
$mf = min($s["Stamp"], time());
$o8 = (int) $s["LastModified"];
$ob = ia($s);
$sf = ff($s);
if ($s["IsPublished"]) {
$as_ = $_strings["pt--edit-post"];
$p8 = "";
$ry = e2_alias_of_note_with_id_($s["ID"]);
} else {
$as_ = $_strings["pt--edit-draft"];
$p8 = d(USER_DIR, bl(), "find", "n", $s["ID"], $s["Title"]);
if (@$s["OriginalAlias"]) {
$ry = $s["OriginalAlias"];
} else {
$ry = $p8;
}
}
$note_id = $s["ID"];
$i8 = $s["FormatterID"];
$ss = $s["Title"];
}
$cg = sa();
$vg = [];
if ($cg !== null) {
foreach ($cg as $gv) {
$vg[] = $gv["tag-dotted"];
}
}
$bg = [];
if ($ds == "edit" and count($vg)) {
$cg = ba($s["ID"]);
foreach ($cg as $wb) {
$bg[] = ka($wb);
}
}
$yg = [];
foreach ($vg as $ng) {
$mg["tag-dotted"] = $ng;
$mg["selected?"] = in_array($ng, $bg);
$yg[] = $mg;
}
$bg = implode(", ", $bg);
$v3 = [];
if ($ds == "write") {
$zs = $_strings["fb--save-and-preview"];
$fg = "";
if (is_file(USER_DIR . "new-uploads.psa")) {
$fg = @file_get_contents(USER_DIR . "new-uploads.psa");
}
$y3 = @unserialize($fg);
}
if ($ds == "edit") {
if (array_key_exists("draft", $parameters)) {
$zs = $_strings["fb--save-and-preview"];
} else {
$zs = $_strings["fb--save-changes"];
}
$v3 = qy($s["FormatterID"], $s["Text"]);
($y3 = @unserialize($s["Uploads"])) or ($y3 = []);
}
$dg = e2_(l2(k2($v3, $y3)));
if ($ds == "edit") {
i3("Notes", $s, $v3);
}
$yk = vy();
$nk = by($yk);
$vb["title"] = $ss;
$vb["heading"] = $as_;
$vb["form"] = "form-note";
$vb["uploads"] = [
"enabled?" => $nk,
"each" => $dg,
"default-name" => htmlspecialchars($ry, ENT_COMPAT, "UTF-8"),
"upload-action" => eq("e2j_file_upload"),
"rename-action" => eq("e2j_file_rename"),
"remove-action" => eq("e2j_file_remove"),
];
$vb["form-note"] = [
".note-id" => $note_id,
".formatter-id" => $i8,
".last-modified-stamp" => $o8,
".published?" => (bool) @$s["IsPublished"],
".old-tags-hash" => md5($bg),
".action" => $ds,
"form-action" => eq("e2s_note_process"),
"form-note-livesave-action" => eq("e2j_note_livesave"),
"create:edit?" => (bool) ($ds == "write"),
"title" => htmlspecialchars((string) @$s["Title"], ENT_COMPAT, "UTF-8"),
"tags-info" => $yg,
"text" => htmlspecialchars((string) @$s["Text"], ENT_NOQUOTES, "UTF-8"),
"stamp-formatted" => y1("d.m.Y H:i:s", $mf, $ob),
"time" => @$s["IsPublished"] ? [(int) $mf, $ob] : false,
"draft?" => $sf === "draft",
"uploads-enabled?" => $nk,
"summary" => (string) @$s["Summary"],
"alias-autogenerated" => htmlspecialchars($p8, ENT_COMPAT, "UTF-8"),
"alias" => htmlspecialchars($ry, ENT_COMPAT, "UTF-8"),
"submit-text" => $zs,
"space-usage" => yy($yk),
];
if ($ds == "edit") {
$vb["related-delete-href"] = eq("e2m_note_delete", ["*note" => $s]);
}
return $vb;
}
function e2m_note_edit($parameters = [])
{
return hm("edit", $parameters);
}
function e2m_write()
{
return hm("write");
}
function e2s_note_process()
{
global $_strings;
try {
$sg = yf();
$note_id = $sg["data"]["id"];
$zy = wm($note_id);
z1(eq("e2m_note", ["*note" => $zy]));
} catch (AeFormIncompleteException $e) {
hb($_strings["er--post-must-have-title-and-text"], E2E_USER_ERROR);
if ($e->note_id === "new") {
z1(eq("e2m_write"));
} else {
z1(eq("e2m_note_edit", ["*note" => wm($e->note_id)]));
}
} catch (AeMySQLException $e) {
v3($e, "Could not process note");
z1();
}
die();
}
function e2s_note_publish()
{
global $_config, $settings;
$databaseConfiguration = bl();
od();
$note_id = "";
if (array_key_exists("note-id", $_POST)) {
$note_id = trim($_POST["note-id"]);
}
if (!is_numeric($note_id) and $note_id !== "new") {
throw new AeFormInconsistentException();
}
$ag = false;
$s = wm($note_id);
if (!$s) {
z1();
}
$qg = $s["OriginalAlias"];
$lg = $s["Stamp"];
$zg = !$s["IsExternal"];
$s["ID"] = $note_id;
$s["IsVisible"] = 1;
$s["IsPublished"] = 1;
$s["IsCommentable"] = (int) $settings["comments"]["default_on"];
if (array_key_exists("browser-offset", $_POST)) {
$ob = l1(@$_POST["browser-offset"]);
ua($ob);
} else {
$ob = pa();
}
if ($ag and ($mf = bf($ag, $ob))) {
$s["Stamp"] = $mf;
} elseif ($zg) {
$s["Stamp"] = time();
} else {
$s["Stamp"] = $lg;
}
if (xd($s)) {
$s["IsIndexed"] = "1";
}
if ($ob) {
$s["Offset"] = (int) $ob["offset"];
$s["IsDST"] = (int) $ob["is_dst"];
}
e2_drop_caches_for_note_($note_id, null);
fm($databaseConfiguration, "Notes", $s);
$ry = "";
if ($qg or $qg === "0") {
$ry = d(USER_DIR, $databaseConfiguration, "set", "n", $note_id, $qg);
$s["OriginalAlias"] = $ry;
}
if ($ry != $qg) {
fm($databaseConfiguration, "Notes", $s);
}
$sf = ff($s);
if ($sf === "public") {
hv($s);
}
z1(eq("e2m_note", ["*note" => $s]));
}
function gm($note_id, $kg = -1)
{
global $_config;
$ms = true;
if ($kg) {
$ms = false;
}
if ($kg === -1) {
$ms = null;
}
e2_drop_caches_for_note_($note_id, $ms);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
((int) $note_id) .
"'",
"delete note by ID"
);
ed($note_id);
e2_delete_aliases_for_entity_("n", $note_id);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"NotesKeywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
((int) $note_id),
"delete tag bindings after deleting note"
);
}
function e2s_note_delete()
{
od();
$note_id = "";
if (array_key_exists("note-id", $_POST)) {
$note_id = trim($_POST["note-id"]);
}
if (!is_numeric($note_id) and $note_id !== "new") {
throw new AeFormInconsistentException();
}
$kg = (bool) $_POST["is-draft"];
$s = wm($note_id);
if ($s) {
$h8 = eq("e2m_note_broadcast", ["*note" => $s]);
gm($note_id, $kg);
vv($h8);
}
if ($kg) {
z1(eq("e2m_drafts", ["page" => 1]));
} else {
z1();
}
die();
}
function e2j_note_livesave()
{
try {
$sg = yf();
} catch (AeFormIncompleteException $e) {
$sg = [
"success" => false,
"error" => ["message" => "Title or text is empty"],
];
} catch (AeRecordNotFoundException $e) {
$sg = [
"success" => false,
"error" => ["message" => "Record not found"],
];
} catch (AeMySQLException $e) {
v3($e);
$sg = ["success" => false, "error" => ["message" => "Database error"]];
}
echo json_encode($sg);
die();
}
function wm($ey)
{
global $_config;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
$ey .
"'"
);
$kb = qm();
if (count($kb) > 0) {
return $kb[0];
} else {
return false;
}
}
function um($zy, $xg, $eg = 1)
{
global $_config;
$qj = $xg == "next" ? ">" : "<";
$rg = $xg == "next" ? "" : "DESC ";
try {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=" .
$eg .
" " .
"AND (" .
"`Stamp` " .
$qj .
" '" .
$zy["Stamp"] .
"' " .
"OR (`Stamp` = '" .
$zy["Stamp"] .
"' AND `ID` " .
$qj .
$zy["ID"] .
")" .
") " .
df(ys()) .
"ORDER BY `Stamp` " .
$rg .
", `ID` " .
$rg .
"LIMIT 1",
"get " . $xg . " note"
);
$kb = qm();
if (count($kb) > 0) {
return $kb[0];
} else {
return false;
}
} catch (AeMySQLException $e) {
v3($e, "Could not get " . $xg . " note");
return null;
}
}
function im($tg)
{
global $_config;
if (Log::$a) {
__log("Lastmodifieds for Local Copier");
}
$tg = (string) $tg;
$tg = preg_replace("[^0-9,]", "", $tg);
$tg = trim($tg, ",");
if (
CACHE_LASTMODIFIEDS and is_file(USER_DIR . CACHE_FILENAME_LASTMODIFIEDS)
) {
$jg = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_LASTMODIFIEDS)
);
if ($jg["ids_csv"] == $tg) {
if (Log::$a) {
__log("Returned from cache");
}
return $jg["lastmodifieds_json"];
}
}
$m1 = "`ID`=" . str_replace(",", " OR `ID`=", $tg);
$hg = [];
sm(
"SELECT `ID`, `LastModified` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (" .
$m1 .
")",
"get lastmodifieds for Local Copier"
);
if (Log::$a) {
__log("Requested from DB");
}
$h3 = qm();
foreach ($h3 as $k3 => $x3) {
$hg[(int) $x3["ID"]] = (int) $x3["LastModified"];
}
$gg = json_encode($hg);
if ($gg == "[]") {
$gg = "{}";
}
$jg = ["ids_csv" => $tg, "lastmodifieds_json" => $gg];
if (CACHE_LASTMODIFIEDS) {
e3(USER_DIR . CACHE_FILENAME_LASTMODIFIEDS, serialize($jg));
}
return $gg;
}
function om($gm, $wm, $um = false)
{
global $_config;
list($en, $rn) = s1($gm, $wm, $um);
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` AND (`Stamp` BETWEEN " .
$en .
" AND " .
$rn .
") " .
"ORDER BY Stamp",
"get all notes for the date " . $um . "." . $wm . "." . $gm
);
$vb = [];
foreach (qm() as $lf) {
if (is_numeric($um)) {
$l1 =
((int) $gm) . "/" . ((int) $wm) . "/" . ((int) $um) ==
y1("Y/n/j", $lf["Stamp"], ia($lf));
} elseif (is_numeric($wm)) {
$l1 =
((int) $gm) . "/" . ((int) $wm) ==
y1("Y/n", $lf["Stamp"], ia($lf));
} else {
$l1 = ((int) $gm) == y1("Y", $lf["Stamp"], ia($lf));
}
if ($l1) {
$vb[] = $lf;
}
}
return $vb;
}
function e2_published_noterec_with_parameters_($parameters = [])
{
$zy = e2_noterec_with_parameters_($parameters);
if ($zy and $zy["IsPublished"]) {
return $zy;
}
}
function e2_noterec_with_parameters_($parameters = [])
{
global $_config;
$zy = false;
$ug = false;
if ((string) @$parameters["oalias"] !== "") {
$ug = $parameters["oalias"];
}
if ((string) $ug !== "") {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `OriginalAlias` = '" .
$ug .
"' " .
"AND `IsPublished` = 0",
"get note record by original alias"
);
$zy = qm();
if (count($zy) === 1) {
$zy = @$zy[0];
if ($zy) {
return $zy;
}
}
}
$ig = false;
if (@$parameters["draft"] !== "") {
$ig = @$parameters["draft"];
}
if (@$parameters["draft2"] !== "") {
$ig = @$parameters["draft2"];
}
if ($ig) {
$zy = wm($ig);
return $zy;
}
if ((string) $ug !== "") {
$parameters["alias"] = $ug;
}
if ((string) @$parameters["alias"] !== "") {
if ($og = f(@$parameters["alias"])) {
if ($og["type"] == "n") {
$zy = wm($og["id"]);
if ($zy and $zy["IsPublished"]) {
return $zy;
}
}
}
}
if (
(string) @$parameters["year"] !== "" and
(string) @$parameters["month"] !== "" and
(string) @$parameters["day"] !== ""
) {
$ff = om($parameters["year"], $parameters["month"], $parameters["day"]);
if (@$ff[$parameters["day-number"] - 1]) {
return $ff[$parameters["day-number"] - 1];
}
}
return null;
}
function vf($ss, $e1, $ob, $fg)
{
$databaseConfiguration = bl();
vb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
$zy = [
"Title" => $ss,
"Text" => $e1,
"FormatterID" => DEFAULT_FORMATTER,
"OriginalAlias" => d(
USER_DIR,
$databaseConfiguration,
"find",
"",
"",
$ss
),
"Uploads" => $fg,
"IsPublished" => 0,
"Stamp" => (int) time(),
"LastModified" => (int) time(),
];
if ($ob and is_array($ob)) {
$zy["Offset"] = (int) $ob["offset"];
$zy["IsDST"] = (int) $ob["is_dst"];
}
return mm($databaseConfiguration, "Notes", $zy);
}
function bf($pg, $ob)
{
$cw =
'/^ *(\d{1,2})\.(\d{1,2})\.(\d{2}|\d{4}) +(\d{1,2})\:(\d{1,2})\:(\d{1,2}) *$/';
if (preg_match($cw, (string) @$pg, $wm)) {
$mf = gmmktime(
(int) $wm[4],
(int) $wm[5],
(int) $wm[6],
(int) $wm[2],
(int) $wm[1],
(int) $wm[3]
);
$mf -= v1($ob, $mf);
return $mf;
} else {
return false;
}
}
function yf()
{
global $_config;
if (Log::$a) {
__log("Process note form");
}
od();
$note_id = $ss = $vw = $e1 = $bw = $yw = "";
if (array_key_exists("note-id", $_POST)) {
$note_id = trim($_POST["note-id"]);
}
if (array_key_exists("title", $_POST)) {
$ss = trim($_POST["title"]);
}
if (array_key_exists("tags", $_POST)) {
$vw = $_POST["tags"];
}
if (array_key_exists("text", $_POST)) {
$e1 = trim($_POST["text"], "\r\n");
}
if (array_key_exists("summary", $_POST)) {
$bw = trim($_POST["summary"], "\r\n");
}
if (array_key_exists("old-tags-hash", $_POST)) {
$yw = $_POST["old-tags-hash"];
}
if (!is_numeric($note_id) and $note_id !== "new") {
throw new AeFormInconsistentException();
}
if ((string) $ss === "" or (string) $e1 === "") {
throw new AeFormIncompleteException($note_id);
}
$nw = $e1;
$nw = str_replace("\n", '\n' . "\n", $nw);
$nw = str_replace("\r", '\r' . "\r", $nw);
if (!is_array($vw)) {
$vw = [];
}
$vw = trim(implode(", ", $vw));
$n6 = r1(",", $vw, "sort");
$vw = implode(", ", $n6);
$mw = md5($vw);
if (array_key_exists("browser-offset", $_POST)) {
$fw = l1(@$_POST["browser-offset"]);
ua($fw);
} else {
$fw = pa();
}
$dw = (string) @$_POST["old-stamp"];
$ag = (string) @$_POST["stamp"];
$ry = @$_POST["alias"];
$databaseConfiguration = bl();
if ($note_id == "new") {
$fg = "";
if (is_file(USER_DIR . "new-uploads.psa")) {
$fg = @file_get_contents(USER_DIR . "new-uploads.psa");
}
$zy = vf($ss, $e1, $fw, $fg);
$note_id = (int) $zy["ID"];
@unlink(USER_DIR . "new-uploads.psa");
$h3 = [
"success" => true,
"data" => [
"status" => "created",
"id" => $note_id,
"note-url" => eq("e2m_note", ["*note" => $zy]),
"note-edit-url" => eq("e2m_note_edit", ["*note" => $zy]),
],
];
} else {
$sw = wm($note_id);
if (!$sw) {
throw new AeRecordNotFoundException();
}
e2_drop_caches_for_note_($note_id, $sw["IsPublished"]);
$aw = $sw;
$aw["ID"] = $note_id;
$aw["Title"] = $ss;
$aw["Summary"] = $bw;
$aw["Text"] = $e1;
$aw["FormatterID"] = $sw["FormatterID"];
$aw["LastModified"] = time();
$aw["IsIndexed"] = "0";
$qw = ["offset" => $sw["Offset"], "is_dst" => $sw["IsDST"]];
if ($aw["FormatterID"] !== "raw") {
$aw["FormatterID"] = DEFAULT_FORMATTER;
}
if ($dw != $ag) {
if ($mf = bf($ag, $qw)) {
$aw["Stamp"] = min($mf, time());
}
}
$jy = $ry;
if ((string) $ry !== "") {
$lw = $ry;
} elseif (!$sw["IsPublished"]) {
$lw = $ss;
} else {
$lw = "";
}
if ($sw["IsPublished"]) {
$jy = d(
USER_DIR,
$databaseConfiguration,
"set",
"n",
$note_id,
$lw
);
$zw = ["*note" => $aw, "alias" => $jy];
} else {
$jy = d(
USER_DIR,
$databaseConfiguration,
"find",
"n",
$note_id,
$lw
);
$aw["OriginalAlias"] = $jy;
$zw = ["*note" => $aw, "alias" => $jy];
}
$v3 = qy($aw["FormatterID"], $aw["Text"]);
if (count($v3) > 0) {
g2($v3);
w2($v3);
}
fm($databaseConfiguration, "Notes", $aw);
if ($aw["IsPublished"]) {
if (xd($aw)) {
$aw["IsIndexed"] = "1";
fm($databaseConfiguration, "Notes", $aw);
}
if ($dw != $ag) {
b(true);
}
}
$h3 = [
"success" => true,
"data" => [
"status" => "saved",
"id" => (int) $aw["ID"],
"new-alias" => $jy,
"note-url" => eq("e2m_note", $zw),
"note-edit-url" => eq("e2m_note_edit", $zw),
],
];
}
if ($mw != $yw) {
ya($databaseConfiguration, $note_id, $n6);
}
if (isset($aw)) {
hv($aw);
}
if ($_config["backup_automatically"]) {
zm();
}
return $h3;
}
function nf($kw, $xw)
{
global $_config;
if (!($kw and $xw) and !ys()) {
if (Log::$a) {
__log(
"Error: e2_notes_count_generic called for invisible items unsecurely"
);
}
return null;
}
if (!is_bool($kw) or !is_bool($xw)) {
if (Log::$a) {
__log("Error: e2_notes_count_generic called with non-bool params");
}
return null;
}
if (!$kw and !$xw) {
if (Log::$a) {
__log(
"Error: e2_notes_count_generic called with nonsensical parameters"
);
}
return null;
}
$of =
USER_DIR .
CACHES_DIRNAME .
"notes-count-p" .
(int) $kw .
($kw ? "v" . (int) $xw : "") .
".txt";
$h3 = false;
if (CACHE_NOTES_COUNTS and is_file($of)) {
$h3 = (int) @file_get_contents($of);
}
if (is_numeric($h3) and $h3 > 0) {
return $h3;
} else {
$h3 = null;
try {
sm(
"SELECT COUNT(*) As NotesCount FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=" .
(int) $kw .
" " .
($kw ? "AND `IsVisible`=" . (int) $xw : ""),
"count notes with flags p" .
(int) $kw .
($kw ? "v" . (int) $xw : "")
);
$h3 = qm();
$h3 = (int) $h3[0]["NotesCount"];
if (CACHE_NOTES_COUNTS) {
e3($of, $h3);
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Could not count notes");
}
}
return $h3;
}
}
function mf($e1)
{
$bw = $e1;
$bw = preg_match(
'/^(\<\/div\>)?\<p( class\=\"lead\")?\>(.*)\<\/p\>$/mu',
$bw,
$v6
);
$bw = @$v6[3];
if (!$bw) {
$bw = $e1;
}
if (mb_strlen($bw) <= 50) {
$bw = $e1;
}
$bw = str_replace(
["<p>", "<blockquote>", "<ul>", "<ol>", "<br />"],
"\n",
$bw
);
$bw = trim(strip_tags($bw));
if (mb_strlen($bw) > 50) {
$ew = mb_strpos($bw, "\n", 50);
} else {
$ew = mb_strrpos($bw, "\n");
}
if ($ew !== false) {
$bw = mb_substr($bw, 0, $ew);
$bw = trim($bw, " :.()" . "\n");
}
if (preg_match("/^(.{100,}?)(?:[:.!?()]|" . "\n" . ")/su", $bw, $v6)) {
$bw = trim($v6[0], " :.()" . "\n");
}
if (preg_match("/^(.{150,}?)[:.!?(),]/su", $bw, $v6)) {
$bw = trim($v6[0], " :.()," . "\n");
}
if (preg_match("/^(.{200,}?)[:.!?(), ]/su", $bw, $v6)) {
$bw = trim($v6[0], " :.()" . "\n");
}
$bw = preg_replace('/[ \n\r\t]+/su', " ", $bw);
if (mb_substr($bw, -1) === ".") {
$bw = mb_substr($bw, 0, -1);
}
if (mb_substr($bw, -1) === ":") {
$bw = mb_substr($bw, 0, -1);
}
if (mb_substr($bw, -1) === "!") {
$bw = mb_substr($bw, 0, -1);
}
if (@in_array($bw[mb_strlen($bw) - 1], [",", " "])) {
$bw = trim($bw, ", ") . "...";
}
if (mb_strlen($bw) > 250) {
$bw = trim(mb_substr($bw, 0, 250)) . "...";
}
return $bw;
}
function ff($zy)
{
$rw = false;
if ($zy["IsPublished"]) {
if ($rw) {
return "scheduled";
} else {
if ($zy["IsVisible"]) {
return "public";
} else {
return "hidden";
}
}
} else {
return "draft";
}
}
function df($gn = false)
{
if ($gn) {
return "";
} else {
return "AND (n.`IsVisible` = 1 AND n.`Stamp` <= " . time() . ") ";
}
}
function sf()
{
global $_config;
if (CACHE_RANDOM_NOTE and is_file(USER_DIR . CACHE_FILENAME_RANDOM_NOTE)) {
$yj = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_RANDOM_NOTE)
);
return $yj;
}
$yj = false;
$tw = nf(true, true);
if ($tw >= 10) {
sm(
"SELECT COUNT(*) as NotesCount FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND n.`IsFavourite` = 1 " .
"AND n.`IsPublished` = 1 " .
"AND n.`IsVisible` = 1 ",
"get the number of visible published favourite notes"
);
$h3 = qm();
$jw = (int) $h3[0]["NotesCount"];
$hw = "";
if ($jw >= 10) {
$hw = "AND n.`IsFavourite` = 1";
}
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
$hw .
" " .
"AND n.`IsPublished` = 1 " .
"AND n.`IsVisible` = 1 " .
"ORDER BY RAND() " .
"LIMIT 1 ",
"get a random visible published and maybe favourite note"
);
$ff = qm();
$yj = eq("e2m_note", ["*note" => $ff[0]]);
}
if (CACHE_RANDOM_NOTE) {
e3(USER_DIR . CACHE_FILENAME_RANDOM_NOTE, serialize($yj));
}
return $yj;
}
function af($zy)
{
return "";
}
define("OLBA_SPECIAL_CHAR", "\x1");
define("OLBA_SPECIAL_SEQUENCE_LENGTH", 6);
function kf($vu = null)
{
global $_template, $settings;
if ($vu === null) {
$vu = @$settings["template"];
}
$bu = null;
$yu = null;
$nu = null;
$mu = [];
$fu = $vu;
if ($fu !== null) {
while (1) {
foreach (
[
USER_DIR . THEMES_DIRNAME,
INSTANCE_DIR . THEMES_DIRNAME,
SYSTEM_DIR . THEMES_DIRNAME,
]
as $du
) {
$su = $du . $fu . "/";
if (is_dir($su) and is_file($su . "/theme-info.php")) {
if (Log::$a) {
__log('Theme "' . $fu . '" found in "' . $su . '"');
}
break;
} else {
$su = false;
}
}
if (!$su) {
if (Log::$a) {
__log(
'Theme "' .
$fu .
'" not found, using default theme "' .
DEFAULT_TEMPLATE .
'"'
);
}
$fu = DEFAULT_TEMPLATE;
$su = $du . $fu . "/";
}
array_push($mu, $su);
$au = include $su . "/theme-info.php";
$qu[$su] = $au;
if (array_key_exists("meta_viewport", $au)) {
if ($bu === null) {
$bu = $au["meta_viewport"];
}
}
if (array_key_exists("supports_dark_mode", $au)) {
if ($yu === null) {
$yu = $au["supports_dark_mode"];
}
}
if (array_key_exists("use_likely_light", $au)) {
if ($nu === null) {
$nu = $au["use_likely_light"];
}
}
if (array_key_exists("based_on", $au)) {
$fu = $au["based_on"];
} else {
break;
}
}
}
if ($bu === null) {
$bu = "";
}
if ($yu === null) {
$yu = false;
}
if ($nu === null) {
$nu = false;
}
$su = SYSTEM_THEME_DIR;
array_push($mu, $su);
$qu[$su] = [];
$_template["name"] = $vu;
$_template["meta_viewport"] = $bu;
$_template["supports_dark_mode"] = $yu;
$_template["use_likely_light"] = $nu;
$_template["stack"] = $mu;
$_template["infos"] = $qu;
}
function xf($lu)
{
global $content;
if (!isset($_olba_includes)) {
$_olba_includes = 0;
}
++$_olba_includes;
if (Log::$a) {
__log('Eat "' . $lu . '"');
}
ob_start();
include $lu;
return ob_get_clean();
}
function ef($mb)
{
return OLBA_SPECIAL_CHAR .
str_pad($mb, OLBA_SPECIAL_SEQUENCE_LENGTH, "0", STR_PAD_LEFT) .
OLBA_SPECIAL_CHAR;
}
function rf($name)
{
static $mb = 0;
f2($name, "_olba_placeholders");
return ef($mb++);
}
function tf($zu)
{
global $_olba_placeholders;
foreach ($_olba_placeholders as $mb => $vv) {
$ku = ef($mb);
$xu = strpos($zu, $ku);
$eu = hf($vv, true);
if ($xu !== false) {
$zu = substr_replace($zu, $eu, $xu, strlen($ku));
} else {
break;
}
}
return $zu;
}
function jf($ru)
{
foreach (
[
USER_DIR . EXTRAS_DIRNAME,
INSTANCE_DIR . EXTRAS_DIRNAME,
SYSTEM_DIR . EXTRAS_DIRNAME,
]
as $tu
) {
if (is_dir($tu)) {
$ju = $tu . $ru . ".tmpl.php";
if (is_file($ju)) {
return xf($ju);
}
}
}
return "";
}
function hf($ru)
{
global $_template, $_olba_includes;
$ju = "templates/" . $ru . ".tmpl.php";
if ($lu = e2o__usable_file_with_basename_($ju)) {
return xf($lu);
} else {
ob_end_clean();
throw new AeOlbaTemplateMissingException("Missing: " . $ju);
}
}
function gf()
{
global $_config;
if (
@$_config["raw_template_data"] or
@$_config["raw_template_data_with_param"] and
array_key_exists("raw", $_GET)
) {
$hu = "raw";
} else {
$hu = "main";
}
return hf($hu, true);
}
function wf($gu)
{
f2($gu . ".css", "_olba_used_stylesheets");
}
function uf($wu)
{
f2($wu . ".js", "_olba_used_scripts");
}
function if_($uu)
{
foreach (
[
SYSTEM_DIR . LIBRARY_DIRNAME,
INSTANCE_DIR . LIBRARY_DIRNAME,
USER_DIR . LIBRARY_DIRNAME,
]
as $iu
) {
foreach (glob($iu . $uu . "/*") as $s2) {
$vz = pathinfo($s2, PATHINFO_EXTENSION);
if ($vz == "js") {
f2($s2, "_olba_used_scripts");
}
if ($vz == "css") {
f2($s2, "_olba_used_stylesheets");
}
}
}
}
function of()
{
global $_template, $settings;
foreach (
[
USER_DIR . THEMES_DIRNAME,
INSTANCE_DIR . THEMES_DIRNAME,
SYSTEM_DIR . THEMES_DIRNAME,
]
as $ou
) {
if ($pu = @opendir($ou)) {
while (false !== ($c0 = readdir($pu))) {
if (is_dir($ou . $c0) and $c0 != "." and $c0 != "..") {
if (is_file($ou . $c0 . "/theme-info.php")) {
$v0[$c0] = $ou . $c0 . "/";
}
}
}
closedir($pu);
}
}
$tv = [];
$b0 = 1000;
foreach ($v0 as $name => $w) {
$au = include $w . "theme-info.php";
$y0 = @$au["display_name"];
if (!$y0) {
continue;
}
if (is_array($y0)) {
if (array_key_exists($settings["language"], $y0)) {
$y0 = $y0[$settings["language"]];
} else {
$y0 = array_shift($y0);
}
}
($mb = @$au["index"]) or ($mb = $b0++);
$n0 = @$au["colors"];
if (!$n0) {
$n0 = [
"background" => "transparent",
"headings" => "rgba(128,128,128,.2)",
"text" => "rgba(128,128,128,.2)",
"link" => "rgba(128,128,128,.2)",
];
}
$m0 = (bool) ($name == $_template["name"]);
if ($m0) {
$f0 = eq("e2m_theme_preview", ["theme" => ""]);
} else {
$f0 = eq("e2m_theme_preview", ["theme" => $name]);
}
$tv[$mb] = [
"name" => $name,
"display-name" => $y0,
"colors" => $n0,
"current?" => $m0,
"preview-url" => $f0,
"supports-dark-mode?" => (bool) @$au["supports_dark_mode"],
];
}
ksort($tv);
return $tv;
}
function pf($od)
{
return e2o__usable_file_with_basename_("images/" . $od);
}
function c2($d0)
{
$s0 = e2o__usable_file_with_basename_("images/" . $d0 . ".svg");
if (is_file($s0)) {
return file_get_contents($s0);
}
return "";
}
function v2($gu)
{
global $_template;
$ud = "styles/" . $gu . ".css";
$a0 = [];
foreach ($_template["stack"] as $su) {
if (is_file($od = $su . $ud)) {
$a0[] = $od;
}
if (
array_key_exists("reset_styles", $_template["infos"][$su]) and
in_array($gu, $_template["infos"][$su]["reset_styles"])
) {
break;
}
}
$a0 = array_reverse($a0);
}
function b2($tv)
{
foreach ($tv as $k3 => $x3) {
$cs = stat($x3);
$tv[$k3] = AeEnv::$o . $tv[$k3] . "?" . $cs["mtime"];
}
return $tv;
}
function y2()
{
global $_olba_used_stylesheets, $_template;
if (!isset($_olba_used_stylesheets)) {
return;
}
$_olba_used_stylesheets = array_unique($_olba_used_stylesheets);
$q0 = [];
foreach ($_olba_used_stylesheets as $gu) {
if (is_file($gu)) {
$q0[] = $gu;
continue;
}
if (is_file($od = USER_DIR . SCRIPTS_SUBDIR . $gu)) {
$q0[] = $od;
}
$ud = "styles/" . $gu;
$a0 = [];
foreach ($_template["stack"] as $su) {
if (is_file($od = $su . $ud)) {
$a0[] = $od;
}
if (
array_key_exists("reset_styles", $_template["infos"][$su]) and
in_array($gu, $_template["infos"][$su]["reset_styles"])
) {
break;
}
}
$a0 = array_reverse($a0);
$q0 = array_merge($q0, $a0);
}
$q0 = b2($q0);
return $q0;
}
function n2()
{
global $_olba_used_scripts;
if (!isset($_olba_used_scripts)) {
return;
}
$_olba_used_scripts = array_unique($_olba_used_scripts);
$l0 = [];
foreach ($_olba_used_scripts as $wu) {
if (
substr($wu, 0, 7) == "http://" or
substr($wu, 0, 8) == "https://" or
substr($wu, 0, 2) == "//"
) {
$l0[] = $wu;
continue;
}
if (is_file($wu)) {
$l0[] = $wu;
continue;
}
if (is_file($z0 = USER_DIR . SCRIPTS_SUBDIR . $wu)) {
$l0[] = $z0;
}
$ud = SCRIPTS_SUBDIR . $wu;
if ($z0 = e2o__usable_file_with_basename_($ud)) {
$l0[] = $z0;
}
}
$l0 = b2($l0);
return $l0;
}
function m2($k0)
{
if (!is_array($k0)) {
return;
}
foreach ($k0 as $ix) {
if (substr($ix, -3) == ".js") {
uf(SYSTEM_DIR . LIBRARY_DIRNAME . substr($ix, 0, -3));
}
if (substr($ix, -4) == ".css") {
wf(SYSTEM_DIR . LIBRARY_DIRNAME . substr($ix, 0, -4));
}
}
}
function f2($vv, $ys)
{
if (!isset($GLOBALS[$ys])) {
$GLOBALS[$ys] = [$vv];
} else {
$GLOBALS[$ys][] = $vv;
}
}
function e2o__usable_file_with_basename_($ud)
{
global $_template;
if (!isset($_template)) {
kf();
}
foreach ($_template["stack"] as $su) {
if (is_file($od = $su . $ud)) {
return $od;
}
}
return "";
}
function e2m_theme_preview($parameters)
{
global $_lang, $_strings, $_config, $settings, $_template;
if (!$_config["allow_themes_preview"]) {
return e2m_error404();
}
if ((string) $parameters["theme"] !== "") {
kf($parameters["theme"]);
} else {
kf();
}
if ($parameters["theme"] == @$settings["template"]) {
z1(eq("e2m_theme_preview", ["theme" => ""]));
}
$ve = $_lang;
if (!is_file($s2 = "system/preview/" . $ve . ".php")) {
$ve = $_strings["--secondary-language"];
$s2 = "system/preview/" . $ve . ".php";
}
if (!is_file($s2 = "system/preview/" . $ve . ".php")) {
$s2 = "system/preview/" . DEFAULT_LANGUAGE . ".php";
}
$v = include $s2;
return $v;
}
function e2m_popular($parameters = [])
{
global $settings, $_config, $_strings;
$gn = ys();
$popularView = new AePageableNotesView("e2m_popular", $parameters);
$popularView->setPortionSize($settings["appearance"]["notes_per_page"]);
$popularView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$popularView->setWantNewCommentsCount($gn);
$popularView->setWantReadHrefs($_config["count_reads"]);
$popularView->setWantControls($gn and !@$_config["read_only"]);
$popularView->setWantHiddenTags($gn);
AeMainMenuManager::$isPopularCurrent = true;
$sl = $_config["popular_period"];
if ($sl === "ever") {
$popularView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df($gn) .
"ORDER BY `ReadCount` DESC"
);
} else {
$al = time() - n3($_config["popular_period"]);
$x0 =
"FROM `" .
$_config["db_table_prefix"] .
"Actions` a, " .
"`" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE a.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND a.`Stamp` > " .
$al .
" " .
"AND n.`IsPublished` = 1 " .
df($gn) .
"AND a.`EntityID` = n.`ID` " .
"GROUP BY a.`EntityID`";
$popularView->setSQLCountRequest(
"SELECT COUNT(*) Total FROM (SELECT 1 " . $x0 . ") _"
);
$popularView->setLimitlessSQLRequest(
"SELECT n.*, a.`EntityID`, SUM(a.`ReadCount`) `AggregateReadCount` " .
$x0 .
" " .
"ORDER BY `AggregateReadCount` DESC"
);
}
$vb = [
"title" => e2l_get_string("pt--most-read", ["period" => $sl]),
"heading" => e2l_get_string("pt--most-read", ["period" => $sl]),
"notes" => $popularView->getNotesCTree(),
"pages" => $popularView->getPagesCTree(),
];
if ($popularView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-such-notes"];
} elseif (!$popularView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function s2($fs = false, $l3 = [])
{
global $_config, $_current_url;
$e0 = $r0 = "";
$mostReadNotesCollectionView = new AeArbitraryNotesCollectionView(
"most read or most read by tag"
);
$mostReadNotesCollectionView->setCurrentURL($_current_url);
$mostReadNotesCollectionView->setFilterOutIDs($l3);
$al = time() - n3($_config["popular_period"]);
$mostReadNotesCollectionView->setSQLRequest(
"SELECT n.*, a.`EntityID`, SUM(a.`ReadCount`) `AggregateReadCount` " .
"FROM `" .
$_config["db_table_prefix"] .
"Actions` a, " .
"`" .
$_config["db_table_prefix"] .
"Notes` n " .
$e0 .
"WHERE a.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
$r0 .
"AND a.`Stamp` > " .
$al .
" " .
"AND n.`IsPublished` = 1 " .
"AND n.`IsFavourite` = 1 " .
df(ys()) .
"AND a.`EntityID` = n.`ID` " .
"GROUP BY a.`EntityID` " .
"ORDER BY `IsFavourite` DESC, `AggregateReadCount` DESC " .
"LIMIT 10"
);
if ($fs === false) {
if (CACHE_POPULAR) {
$mostReadNotesCollectionView->setViewExpiration(SECONDS_IN_A_DAY);
$mostReadNotesCollectionView->setCacheFilename(
USER_DIR . CACHE_FILENAME_POPULAR
);
$mostReadNotesCollectionView->setCacheExpiresFilename(
USER_DIR . CACHE_FILENAME_POPULAR_EXPIRES
);
}
} else {
if (CACHE_POPULAR_WITH_TAG) {
$mostReadNotesCollectionView->setViewExpiration(SECONDS_IN_A_DAY);
$mostReadNotesCollectionView->setCacheFilename(
e2_cache_filename_with_id_(
$fs,
USER_DIR . CACHE_FILENAMES_POPULAR_WITH_TAG
)
);
$mostReadNotesCollectionView->setCacheExpiresFilename(
e2_cache_filename_with_id_(
$fs,
USER_DIR . CACHE_FILENAMES_POPULAR_WITH_TAG_EXPIRES
)
);
}
}
return $mostReadNotesCollectionView->getNotesCTree();
}
function a2($fs = false, $l3 = [])
{
global $_strings;
$t0 = ["title" => $_strings["nm--most-read"]];
$t0["each"] = s2($fs, $l3);
if ($fs) {
$t0["seed"] = $fs;
}
if (count($t0["each"]) < 7) {
return [];
}
return $t0;
}
function e2s_post_service($parameters)
{
global $_config;
$j0 = eq("e2m_settings");
if ($_config["allow_underhood_access"]) {
$j0 = eq("e2m_underhood");
}
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1($j0);
}
if ($_config["allow_underhood_access"]) {
if ($parameters["service"] === "build") {
od();
e2_build();
hb("Engine core built", E2E_MESSAGE);
}
if ($parameters["service"] === "sync") {
od();
e2_drop_all_kinds_of_cache();
hb("Caches invalidated", E2E_MESSAGE);
}
if ($parameters["service"] === "checklist-reset") {
od();
js();
hb("Checklist reset", E2E_MESSAGE);
}
if ($parameters["service"] === "log") {
od();
zn();
hb("Logs enabled", E2E_MESSAGE);
}
if ($parameters["service"] === "unlog") {
od();
bq(INSTANCE_DIR . LOGS_DIRNAME . "*");
hb("All logs deleted", E2E_MESSAGE);
}
if ($parameters["service"] === "migrate") {
od();
wn(bl());
hb("Database structure up to date", E2E_MESSAGE);
}
}
if ($parameters["service"] === "backup") {
}
z1($j0);
}
define("PROVIDE_MEDIA_ASYNC", 10);
define("PROVIDE_MEDIA_NOW", 20);
function q2($h0)
{
global $_config;
$g0 = parse_url($h0);
if (isset($g0["host"])) {
$url = $h0;
if ($g0["host"] == "www.youtube.com") {
$ey = basename($g0["path"]);
$w0 = "remote/youtube-" . $ey . "-cover.jpg";
$u0 = $_config["path_media"] . PICTURES_DIRNAME . $w0;
$i0 = i2($w0);
return [
"url" => $url,
"type" => "online-video",
"is-local?" => false,
"is-usable-as-cover?" => true,
"is-using-thumbnails?" => true,
"is-generating-thumbnail?" => true,
"is-snippetable?" => true,
"is-rss-enclosure?" => false,
"video-service" => "youtube",
"video-id" => $ey,
"local-cover-href" => AeEnv::$o . PICTURES_DIRNAME . $w0,
"local-relative-filename" => $w0,
"local-full-filename" => $u0,
"local-full-failname" => $u0 . ".failed",
"local-full-thumb-filename" => $i0,
];
} elseif ($g0["host"] == "player.vimeo.com") {
$ey = basename($g0["path"]);
$w0 = "remote/vimeo-" . $ey . "-cover.jpg";
$u0 = $_config["path_media"] . PICTURES_DIRNAME . $w0;
$i0 = i2($w0);
return [
"url" => $url,
"type" => "online-video",
"is-local?" => false,
"is-usable-as-cover?" => true,
"is-using-thumbnails?" => true,
"is-generating-thumbnail?" => true,
"is-snippetable?" => true,
"is-rss-enclosure?" => false,
"video-service" => "vimeo",
"video-id" => $ey,
"local-cover-href" => AeEnv::$o . PICTURES_DIRNAME . $w0,
"local-relative-filename" => $w0,
"local-full-filename" => $u0,
"local-full-failname" => $u0 . ".failed",
"local-full-thumb-filename" => $i0,
];
} elseif (cd($g0["path"])) {
return [
"url" => $url,
"type" => "remote-image",
"is-local?" => false,
"is-usable-as-cover?" => false,
"is-using-thumbnails?" => false,
"is-generating-thumbnail?" => false,
"is-snippetable?" => false,
"is-rss-enclosure?" => false,
"mime-type" => dd($g0["path"]),
"length" => "",
];
} else {
return [
"url" => $url,
"type" => "remote-non-image",
"is-local?" => false,
"is-usable-as-cover?" => false,
"is-using-thumbnails?" => false,
"is-generating-thumbnail?" => false,
"is-snippetable?" => false,
"is-rss-enclosure?" => true,
"mime-type" => dd($g0["path"]),
"length" => "",
];
}
} else {
if (cd($g0["path"])) {
$url = AeEnv::$o . PICTURES_DIRNAME . $g0["path"];
$o0 = $_config["path_media"] . PICTURES_DIRNAME;
$u0 = $o0 . $g0["path"];
$p0 = vd($g0["path"]);
if ($p0) {
$i0 = i2($g0["path"]);
} else {
$i0 = $u0;
}
return [
"url" => $url,
"type" => "local-image",
"is-local?" => true,
"is-usable-as-cover?" => true,
"is-using-thumbnails?" => true,
"is-generating-thumbnail?" => $p0,
"is-snippetable?" => true,
"is-rss-enclosure?" => false,
"mime-type" => dd($g0["path"]),
"length" => @stat($u0)["size"],
"local-href" => $url,
"local-cover-href" => $url,
"default-filename" => "image",
"local-folder" => $o0,
"local-relative-filename" => $g0["path"],
"local-full-filename" => $u0,
"local-full-thumb-filename" => $i0,
];
} elseif (yd($g0["path"])) {
$url = AeEnv::$o . VIDEO_DIRNAME . $g0["path"];
$o0 = $_config["path_media"] . VIDEO_DIRNAME;
$u0 = $o0 . $g0["path"];
return [
"url" => $url,
"type" => "local-video",
"is-local?" => true,
"is-usable-as-cover?" => false,
"is-using-thumbnails?" => true,
"is-generating-thumbnail?" => false,
"is-snippetable?" => false,
"is-rss-enclosure?" => true,
"mime-type" => dd($g0["path"]),
"length" => @stat($u0)["size"],
"local-href" => $url,
"default-filename" => "video",
"local-folder" => $o0,
"local-relative-filename" => $g0["path"],
"local-full-filename" => $u0,
"local-full-thumb-filename" =>
SYSTEM_THEME_DIR . VIDEO_ICON_FILENAME,
];
} else {
$url = AeEnv::$o . AUDIO_DIRNAME . $g0["path"];
$o0 = $_config["path_media"] . AUDIO_DIRNAME;
$u0 = $o0 . $g0["path"];
return [
"url" => $url,
"type" => "local-audio",
"is-local?" => true,
"is-usable-as-cover?" => false,
"is-using-thumbnails?" => true,
"is-generating-thumbnail?" => false,
"is-snippetable?" => false,
"is-rss-enclosure?" => true,
"mime-type" => dd($g0["path"]),
"length" => @stat($u0)["size"],
"local-href" => $url,
"default-filename" => "audio",
"local-folder" => $o0,
"local-full-filename" => $u0,
"local-full-thumb-filename" =>
SYSTEM_THEME_DIR . AUDIO_ICON_FILENAME,
];
}
}
}
function l2($q4)
{
$c9 = [];
foreach ($q4 as $h0) {
$o4 = q2($h0);
if ($o4["is-local?"]) {
$c9[] = $h0;
}
}
return $c9;
}
function z2($q4)
{
$c9 = [];
foreach ($q4 as $h0) {
$o4 = q2($h0);
if ($o4["is-snippetable?"]) {
$c9[] = $h0;
}
}
return $c9;
}
function k2($v3, $y3)
{
if (!is_array($v3)) {
$v3 = [];
}
if (!is_array($y3)) {
$y3 = [];
}
$q4 = array_merge($y3, $v3);
$q4 = array_reverse($q4);
$q4 = array_unique($q4);
$q4 = array_reverse($q4);
return $q4;
}
function x2($q4)
{
if (!is_array($q4) or !count($q4)) {
return [];
}
w2($q4);
$v9 = [];
foreach ($q4 as $h0) {
if (!empty($b9[$h0])) {
continue;
}
$o4 = q2($h0);
if (!$o4["is-usable-as-cover?"]) {
continue;
}
if (!is_file($o4["local-full-filename"])) {
continue;
}
$size = e2_getimagesize($o4["local-full-filename"]);
list($sz, $az, $gr, $wr) = $size;
$v9[] = [
"src" => $o4["local-cover-href"],
"width" => $sz,
"height" => $az,
"horizontality" => $gr,
"verticality" => $wr,
];
$b9[$h0] = true;
}
return $v9;
}
function e2_($q4)
{
global $_strings;
if (!is_array($q4) or !count($q4)) {
return [];
}
w2($q4);
$y9 = [];
foreach ($q4 as $h0) {
if (!empty($b9[$h0])) {
continue;
}
$o4 = q2($h0);
if (!$o4["is-using-thumbnails?"]) {
continue;
}
if (!is_file($o4["local-full-filename"])) {
continue;
}
$n9 = [
"is-available?" => true,
"src" => "",
"width" => "",
"height" => "",
"original-filename" => "",
"original-filesize" => "",
];
if (!$o4["is-local?"] or is_file($o4["local-full-filename"])) {
if ($o4["is-generating-thumbnail?"]) {
$m9 = u2($o4);
} else {
$m9 = $o4["local-full-thumb-filename"];
}
}
if (empty($m9)) {
$n9["is-available?"] = false;
$m9 = i2($o4["local-relative-filename"]);
}
$n9["src"] = o3($m9);
if ($n9["is-available?"]) {
$size = e2_getimagesize($m9);
list($sz, $az) = $size;
} else {
$sz = $az = "";
}
if (!$sz) {
$sz = THUMB_WIDTH / 2;
}
if (!$az) {
$az = THUMB_HEIGHT / 2;
}
list($sz, $az) = e2_fit_metrics_to_constraints(
[$sz, $az],
[THUMB_WIDTH / 2, THUMB_HEIGHT / 2]
);
$n9["width"] = $sz;
$n9["height"] = $az;
if ($o4["is-local?"]) {
$n9["original-filename"] = $h0;
if (is_file($o4["local-full-filename"])) {
$fz = stat($o4["local-full-filename"])[7];
$fz = round($fz / 1024) . " " . $_strings["gs--kb"];
$n9["original-filesize"] = $fz;
}
}
$y9[] = $n9;
$b9[$h0] = true;
}
return $y9;
}
function r2($f9)
{
foreach (
["maxresdefault", "hqdefault", "mqdefault", "sddefault", "default"]
as $od
) {
$url = "http://img.youtube.com/vi/" . $f9 . "/" . $od . ".jpg";
if (Log::$a) {
__log("Trying " . $url . "...");
}
$d9 = @file_get_contents($url);
if ($d9 !== false) {
return $d9;
}
}
return false;
}
function t2($s9)
{
$a9 = @unserialize(
file_get_contents("http://vimeo.com/api/v2/video/" . $s9 . ".php")
);
if (!empty($a9[0]["thumbnail_large"])) {
return @file_get_contents($a9[0]["thumbnail_large"]);
}
return false;
}
function j2($o4, $q9)
{
if (is_file($o4["local-full-filename"])) {
if (Log::$a) {
__log("Already exists: " . $o4["local-full-filename"]);
}
} elseif (is_file($o4["local-full-failname"])) {
if (Log::$a) {
__log("Already tried and failed: " . $o4["local-full-filename"]);
}
} else {
if (Log::$a) {
__log("Resource " . $o4["url"] . " is missing a cover, retrieving");
}
if ($q9 == PROVIDE_MEDIA_ASYNC) {
vv(
eq("e2s_retrieve", [
"url" => strtr(base64_encode($o4["url"]), "+/", "-_"),
])
);
}
if ($q9 == PROVIDE_MEDIA_NOW) {
if (Log::$a) {
__log(
'Downloading "' .
$o4["video-service"] .
'" cover as ' .
$o4["local-full-filename"] .
"..."
);
}
if ($o4["video-service"] == "youtube") {
$d9 = r2($o4["video-id"]);
}
if ($o4["video-service"] == "vimeo") {
$d9 = t2($o4["video-id"]);
}
if ($d9 !== false) {
e3($o4["local-full-filename"], $d9);
} else {
e3($o4["local-full-failname"], "");
}
}
}
}
function h2($h0, $q9)
{
$o4 = q2($h0);
if (Log::$a) {
__log("Resource " . $h0 . " is of type " . $o4["type"]);
}
if ($o4["type"] == "local-image") {
u2($o4);
}
if ($o4["type"] == "online-video") {
j2($o4, $q9);
if ($q9 == PROVIDE_MEDIA_NOW and is_file($o4["local-full-filename"])) {
u2($o4);
}
}
if ($o4["type"] == "remote-image") {
}
}
function g2($q4)
{
foreach ($q4 as $h0) {
$o4 = q2($h0);
if (empty($o4["local-full-failname"])) {
continue;
}
if (is_file($o4["local-full-failname"])) {
if (Log::$a) {
__log(
"Deleting " . $o4["local-full-failname"] . " to try again"
);
}
unlink($o4["local-full-failname"]);
}
}
}
function w2($q4)
{
if (!is_array($q4)) {
return;
}
if (Log::$a) {
__log("Asynchronously provide data for resnames {");
}
foreach ($q4 as $h0) {
h2($h0, PROVIDE_MEDIA_ASYNC);
}
if (Log::$a) {
__log("}");
}
}
function u2($o4)
{
if (!$o4["is-generating-thumbnail?"]) {
return false;
}
return e2img_filename_by_processing(
$o4["local-full-filename"],
$o4["local-full-thumb-filename"],
[THUMB_WIDTH, THUMB_HEIGHT],
CROP_NONE,
THUMB_JPG_QUALITY
);
}
function i2($l9)
{
global $_config;
return md(
$_config["path_media"] . THUMBNAILS_DIRNAME . $l9,
"[email protected]"
);
}
function p2($h0)
{
$k9 = pathinfo($h0);
$vz = @$k9["extension"];
return in_array(strtolower($vz), ["jpg", "jpeg"]);
}
function cd($h0)
{
$k9 = pathinfo($h0);
$vz = (string) @$k9["extension"];
return in_array(strtolower($vz), [
"jpg",
"jpeg",
"gif",
"png",
"webp",
"svg",
]);
}
function vd($h0)
{
$k9 = pathinfo($h0);
$vz = (string) @$k9["extension"];
return in_array(strtolower($vz), ["jpg", "jpeg", "gif", "png", "webp"]);
}
function bd($h0)
{
$k9 = pathinfo($h0);
$vz = (string) @$k9["extension"];
return in_array(strtolower($vz), ["svg"]);
}
function yd($h0)
{
$k9 = pathinfo($h0);
$vz = (string) @$k9["extension"];
return in_array(strtolower($vz), ["mp4", "mov"]);
}
function nd($h0)
{
$k9 = pathinfo($h0);
$vz = (string) @$k9["extension"];
return in_array(strtolower($vz), ["mp3"]);
}
function md($h0, $x9)
{
if (empty($x9)) {
return $h0;
}
$e9 = substr($h0, 0, strrpos($h0, "."));
$r9 = $e9 . "." . $x9;
return $r9;
}
function fd($w, $ud)
{
if (!is_file($w . $ud)) {
return $ud;
}
$t9 = strrpos($ud, ".");
$j9 = substr($ud, 0, $t9);
$vz = substr($ud, $t9);
$gb = 0;
while (is_file($w . $j9 . "-" . ++$gb . $vz));
$ud = $j9 . "-" . $gb . $vz;
return $ud;
}
function dd($h0)
{
$k9 = pathinfo($h0);
$vz = @$k9["extension"];
if ($vz == "png") {
return "image/png";
}
if ($vz == "webp") {
return "image/webp";
}
if ($vz == "gif") {
return "image/gif";
}
if ($vz == "jpg" or $vz == "jpeg") {
return "image/jpeg";
}
if ($vz == "mp3") {
return "audio/mpeg";
}
if ($vz == "svg") {
return "image/svg+xml";
}
if ($vz == "mp4") {
return "video/mp4";
}
if ($vz == "mov") {
return "video/quicktime";
}
}
function sd($h9, $g9)
{
return strcasecmp($h9, $g9) === 0;
}
define("SEARCH_EXTRA_PREFIX", "Rose");
define("SEARCH_LIMIT", 20);
define("SEARCH_SNIPPETS_LIMIT", 20);
define("SEARCH_USE_ROSE", 1);
define("SEARCH_USE_MYSQL", 1);
define("BSI_SELECT_PORTION", 10);
define("BSI_GIVE_UP_TIMEOUT", 10);
define("BSI_UNLOCK_TIMEOUT", 10);
use S2\Rose\Storage\Exception\EmptyIndexException;
use S2\Rose\Storage\Database\PdoStorage;
use S2\Rose\Storage\Database\MysqlRepository;
use S2\Rose\Stemmer\PorterStemmerEnglish;
use S2\Rose\Stemmer\PorterStemmerRussian;
use S2\Rose\Indexer;
use S2\Rose\Entity\Indexable;
use S2\Rose\Entity\Query;
use S2\Rose\Entity\ExternalContent;
use S2\Rose\Finder;
use S2\Rose\SnippetBuilder;
function e2m_found($parameters = [])
{
global $_strings, $_config;
$parameters["query"] = trim($parameters["query"]);
$e2_ = $parameters["query"];
if (!$e2_) {
return [
"title" => $_strings["pt--search-query-empty"],
"heading" => $_strings["pt--search"],
"nothing" => $_strings["gs--search-query-empty"],
];
}
$w9 = false;
$u9 = [];
try {
if (ys()) {
$i9 = "";
} else {
$i9 = "AND `IsVisible` = 1 ";
}
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
$i9 .
"AND `Keyword`='" .
lm($e2_) .
"'",
"get tags matching the search query"
);
$jb = qm();
if (isset($jb[0]["ID"])) {
$w9 = [
"href" => eq("e2m_tag", ["*tag" => $jb[0]]),
"name" => htmlspecialchars(
$jb[0]["Keyword"],
ENT_COMPAT,
"UTF-8"
),
"visible?" => (bool) $jb[0]["IsVisible"],
];
$u9 = ma($jb[0]["ID"], 4);
array_unshift($u9, $w9);
}
} catch (AeMySQLException $e) {
v3($e, "Could not get tags matching the search query");
}
$o9 = r1(" ", $parameters["query"]);
if (SEARCH_USE_ROSE) {
$p9 = new PorterStemmerRussian(new PorterStemmerEnglish());
foreach ($o9 as $k3 => $x3) {
$o9[$k3] = $p9->stemWord($o9[$k3]);
}
}
$ci = [];
$gn = ys();
if (SEARCH_USE_ROSE) {
try {
$mt = jd(bl());
$vi = new Finder($mt, $p9);
$vi->setHighlightTemplate("<mark>%s</mark>");
$bi = new Query($e2_);
$bi->setInstanceId($_config["db_table_subset"]);
$bi->setLimit(SEARCH_LIMIT);
$resultSet = $vi->find($bi);
foreach ($resultSet->getFoundExternalIds() as $yi) {
$ni = $yi->getId();
if ($ni[0] == "n") {
$note_id = substr($ni, 1);
$zy = wm($note_id);
if (!empty($_config["search_favourites_boost"])) {
if ($zy["IsFavourite"]) {
$resultSet->setRelevanceRatio(
$ni,
$_config["search_favourites_boost"]
);
}
}
}
}
$snippetBuilder = new SnippetBuilder($p9);
$snippetBuilder->setSnippetLineSeparator(" ");
$snippetBuilder->attachSnippets($resultSet, static function (
array $fi
) use ($gn, $_config) {
$h3 = new ExternalContent();
foreach (array_slice($fi, 0, SEARCH_SNIPPETS_LIMIT) as $yi) {
$ni = $yi->getId();
if ($ni[0] == "n") {
$note_id = substr($ni, 1);
$zy = wm($note_id);
if ($zy) {
$noteView = new AeNoteView($zy);
$noteView->setWantReadHref($_config["count_reads"]);
$noteView->setWantControls(
$gn and !@$_config["read_only"]
);
$noteView->setWantHiddenTags($gn);
$u3 = $noteView->getNoteCTree();
$di[$zy["ID"]] = $u3;
$h3->attach($yi, $u3["text"]);
}
}
}
return $h3;
});
foreach ($resultSet->getItems() as $si) {
$ai = $si->getId();
if ($ai[0] == "n") {
$note_id = substr($ai, 1);
$zy = wm($note_id);
if (!(ff($zy) === "public" or $gn and $zy["IsPublished"])) {
continue;
}
$zy["_"]["_srprovider"] = "Rose";
$zy["_"]["_rose_relevance"] = $si->getRelevance();
$zy["_"]["_rose_title"] = $si->getHighlightedTitle($p9);
$zy["_"]["_rose_snippet"] = $si->getSnippet();
$ci[] = $zy;
}
}
$qi = false;
if (@$_config["dev_rose_info"]) {
$qi = print_r($resultSet->getTrace(), true);
}
} catch (EmptyIndexException $e) {
wd(bl());
ld(USER_DIR);
} catch (AeMySQLException $e) {
v3(
$e,
"Could not do something with the database while working on Rose search results"
);
}
}
if (SEARCH_USE_MYSQL) {
$li = lm(preg_quote($e2_));
$zi = "MySQL FT";
$ki =
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 AND (" .
"MATCH (`Title`, `Text`) AGAINST ('" .
$li .
"')" .
") " .
df($gn) .
"LIMIT " .
SEARCH_LIMIT;
try {
sm($ki, "search using MySQL fulltext search");
$h3 = qm();
foreach ($h3 as $k3 => $zy) {
$zy["_"]["_srprovider"] = $zi;
$ci[] = $zy;
}
} catch (AeMySQLException $e) {
v3($e, "Could not search using MySQL fulltext search");
}
}
$xi = [];
$tn = [];
$gb = 0;
foreach ($ci as $zy) {
if (!in_array($zy["ID"], $xi)) {
if (!empty($di[$zy["ID"]])) {
$r = $di[$zy["ID"]];
} else {
$noteView = new AeNoteView($zy);
$noteView->setWantReadHref($_config["count_reads"]);
$noteView->setWantControls($gn and !@$_config["read_only"]);
$r = $noteView->getNoteCTree();
}
$r["search-result-provider"] = $zy["_"]["_srprovider"];
if ($zy["_"]["_srprovider"] == "Rose") {
$r["search-rose"] = [
"relevance" => $zy["_"]["_rose_relevance"],
"title" => $zy["_"]["_rose_title"],
"snippet" => $zy["_"]["_rose_snippet"],
];
}
if (@$zy["_"]["_rose_title"]) {
$r["title"] = $zy["_"]["_rose_title"];
} else {
$r["title"] = hd($r["title"], $o9);
}
$r["title"] = ay($r["title"]);
if (!empty($zy["_"]["_rose_snippet"])) {
$r["snippet-text"] = $zy["_"]["_rose_snippet"];
} else {
$e1 = $r["text"];
$e1 = preg_replace(
"/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/i",
"",
$e1
);
$e1 = preg_replace(
"/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/i",
"",
$e1
);
$e1 = str_replace(
[
"<br>",
"<br/>",
"<br />",
"</h1>",
"</h2>",
"</h3>",
"</h4>",
"</h5>",
"</h6>",
"</p>",
"</pre>",
"</blockquote>",
"</li>",
],
" ",
$e1
);
$e1 = strip_tags($e1);
$ei = [];
$ri = preg_split('/[\\n\(\)\[\]]|[.:;?!](\s|$)/uis', $e1);
$ti = 0;
$ji = "";
foreach ($ri as $hi) {
$hi = trim($hi);
if (!$hi) {
continue;
}
if (!$ji) {
$ji = $hi;
}
$gi = $hi;
$gi = hd($gi, $o9);
if ($gi != $hi) {
$ei[] = gd($gi);
$ti++;
if ($ti > 3) {
break;
}
}
}
if (count($ei)) {
$r["snippet-text"] = implode(" ", $ei);
} else {
$r["snippet-text"] = $ji;
}
}
$r["has-highlighed-thumbs?"] = false;
if ($v3 = @$r["format-info"]["resources-detected"]) {
$wi = e2_(z2($v3));
foreach ($wi as $k3 => $x3) {
$wi[$k3]["highlighted?"] =
strstr($x3["original-filename"], $e2_) !== false;
if ($wi[$k3]["highlighted?"]) {
$r["has-highlighted-thumbs?"] = true;
}
}
$r["thumbs"] = $wi;
}
$tn[] = $r;
$xi[] = $zy["ID"];
$gb++;
if ($gb >= SEARCH_LIMIT) {
break;
}
}
}
$g2 = count($tn);
if ($g2) {
$ui = e2l_get_string("pt--n-posts", ["number" => $g2]);
} else {
$ui = $_strings["pt--no-posts"];
$vb["nothing"] = $_strings["gs--nothing-found"];
}
if ($gb >= SEARCH_LIMIT) {
$ui = $_strings["gs--many-posts"];
}
if ($u9) {
$vb["search-related-tags"] = $u9;
}
$vb["notes"] = $tn;
$vb["pages"] = [];
$vb["title"] =
$ui .
" " .
$_strings["gs--found-for-query"] .
": " .
htmlspecialchars($e2_, ENT_NOQUOTES, "UTF-8");
$vb["heading"] = $e2_;
if (@$qi) {
$vb["rose-debug-info"] = $qi;
}
return $vb;
}
function ad($parameters)
{
if (Log::$a) {
__log("Search form");
}
$e2_ = trim((string) @$parameters["query"]);
return [
"form-action" => eq("e2s_search"),
"query" => htmlspecialchars($e2_, ENT_COMPAT, "UTF-8"),
];
}
function e2s_search()
{
$e2_ = @$_POST["query"];
$e2_ = str_replace("?", urlencode("?"), (string) @$e2_);
$e2_ = str_replace("/", " ", $e2_);
$e2_ = trim($e2_);
$e2_ = str_replace(" ", "+", $e2_);
z1(eq("e2m_found", ["query" => $e2_]));
}
function qd()
{
global $_config;
sm(
"SELECT COUNT(*) c FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 ",
"count total published notes"
);
$dr = qm();
$ii = $dr[0]["c"];
sm(
"SELECT COUNT(*) c FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsIndexed` = 1 AND `IsPublished` = 1 ",
"count indexed published notes"
);
$dr = qm();
$oi = $dr[0]["c"];
$pi = true;
foreach (td() as $wj) {
if (!bm(bl(), SEARCH_EXTRA_PREFIX . $wj)) {
$pi = false;
break;
}
}
$co = zd(USER_DIR);
if (!$pi) {
$oi = 0;
$co["spent"] = false;
}
$vo = $ii - $oi;
return [
"indexed_count" => $oi,
"total_count" => $ii,
"remaining_count" => $vo,
"time_spent" => @$co["spent"] ? $co["spent"] : false,
];
}
function e2s_bsi_step()
{
global $_config;
$co = zd(USER_DIR);
ignore_user_abort(true);
echo "<pre>";
if ($_config["log_bsi"]) {
Log::$a = true;
if (Log::$a) {
qn("bsi");
}
}
if (Log::$a) {
__log("BSI step");
}
if (
!isset($co["lock"]) or
$co["lock"] < time() - (BSI_GIVE_UP_TIMEOUT + BSI_UNLOCK_TIMEOUT)
) {
if (isset($co["lock"])) {
if (Log::$a) {
__log("Indexer: old lock is " . $co["lock"]);
}
echo "Old lock is " . $co["lock"] . "<br />";
} else {
echo "No old lock<br />";
}
$co["lock"] = time();
if (!@e3(USER_DIR . "bsi.psa", serialize($co))) {
if (Log::$a) {
__log("Indexer: cant get a new lock");
}
die("Cant get a new lock<br />");
}
if (Log::$a) {
__log("Indexer: new lock is " . $co["lock"]);
}
echo "New lock is " . $co["lock"] . "<br /><br />";
try {
$gb = 0;
$bo = 0;
$yo = dq();
$no = false;
$mo = false;
while ($bo < BSI_GIVE_UP_TIMEOUT) {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsIndexed`=0 AND `IsPublished`=1 " .
"ORDER BY `Stamp` DESC " .
"LIMIT " .
BSI_SELECT_PORTION,
"get portion of unindexed notes for indexing"
);
$dr = qm();
if (count($dr)) {
++$gb;
if (Log::$a) {
__log("Indexer: portion " . $gb);
}
echo "Portion " . $gb . "<br />";
foreach ($dr as $s) {
if (Log::$a) {
__log('Indexer: indexing "' . $s["Title"] . '"');
}
echo "Indexing: " . $s["Title"] . "<br />";
if (xd($s)) {
$s["IsIndexed"] = "1";
fm(bl(), "Notes", $s);
} else {
$mo = true;
break 2;
}
if ($_config["broadcast_on_indexing"]) {
wv($s);
}
}
$bo = round(dq() - $yo, 3);
if (Log::$a) {
__log(
"Indexer: steps done " .
count($dr) .
", spent " .
$bo .
" ms so far"
);
}
echo "Steps done " .
count($dr) .
", spent " .
$bo .
" ms so far<br /><br />";
} else {
$no = true;
break;
}
}
if ($no) {
if (Log::$a) {
__log("Indexer: indexing complete");
}
echo "Indexing complete<br /><br />";
if (CACHE_INDEXED_FLAG) {
@e3(USER_DIR . CACHE_FILENAME_INDEXED_FLAG, "");
}
} elseif ($mo) {
if (Log::$a) {
__log("Indexer: indexing failed");
}
echo "Indexing failed<br /><br />";
} else {
if (Log::$a) {
__log("Indexer: time out");
}
echo "Time out<br />";
unset($co["lock"]);
}
if ($co["spent"] !== "?") {
$co["spent"] += $bo;
}
@e3(USER_DIR . "bsi.psa", serialize($co));
} catch (AeMySQLException $e) {
v3($e, "Could not index notes");
if (Log::$a) {
__log("Indexer: DB unaccessible");
}
echo "DB unaccessible<br />";
}
} else {
if (Log::$a) {
__log("Indexer: locked");
}
echo "Locked<br />";
}
die("</pre>");
}
function e2s_reindex()
{
global $_config;
if (!$_config["allow_underhood_access"]) {
z1(eq("e2m_settings"));
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
od();
@unlink(USER_DIR . CACHE_FILENAME_INDEXED_FLAG);
wd(bl(), true);
ld(USER_DIR);
}
z1(eq("e2m_underhood"));
}
function ld($yy)
{
$co = ["spent" => 0];
@e3($yy . "bsi.psa", serialize($co));
return $co;
}
function zd($yy)
{
$co = @unserialize(file_get_contents(USER_DIR . "bsi.psa"));
if (!is_array($co)) {
$co = ld($yy);
}
return $co;
}
function kd()
{
if (
CACHE_INDEXED_FLAG and is_file(USER_DIR . CACHE_FILENAME_INDEXED_FLAG)
) {
return true;
}
$fo = qd();
$ch = $fo["remaining_count"] === 0;
if (CACHE_INDEXED_FLAG and $ch) {
e3(USER_DIR . CACHE_FILENAME_INDEXED_FLAG, "");
}
return $ch;
}
function xd($zy)
{
static $do_ = null;
if (Log::$a) {
__log("Indexer: index noterec");
}
$databaseConfiguration = bl();
try {
if ($do_ === null) {
$p9 = new PorterStemmerRussian(new PorterStemmerEnglish());
$do_ = new Indexer(jd($databaseConfiguration), $p9);
}
$ld = ly($zy["FormatterID"], @$zy["Text"], "full-rss");
r3("note", $zy, $ld["meta"]["resources-detected"]);
$e1 = strip_tags($ld["text-final"]);
$so = new Indexable(
"n" . $zy["ID"],
$zy["Title"],
$e1,
$databaseConfiguration->getSubset()
);
$do_->index($so);
return true;
} catch (EmptyIndexException $e) {
wd(bl());
ld(USER_DIR);
} catch (\Exception $e) {
v3($e, "Could not index note");
return false;
}
}
function ed($ey)
{
global $_config;
static $do_ = null;
$databaseConfiguration = bl();
try {
if ($do_ === null) {
$p9 = new PorterStemmerRussian(new PorterStemmerEnglish());
$do_ = new Indexer(jd($databaseConfiguration), $p9);
}
return $do_->removeById("n" . $ey, $_config["db_table_subset"]);
} catch (EmptyIndexException $e) {
wd($databaseConfiguration);
ld(USER_DIR);
} catch (\Exception $e) {
v3($e, "Could not unindex note");
return false;
}
}
function rd($xx)
{
$prefix = "S2\\Rose\\";
if (BUILT) {
$ex = __DIR__ . "/library/rose/";
} else {
$ex = __DIR__ . "/../library/rose/";
}
$lz = strlen($prefix);
if (strncmp($prefix, $xx, $lz) !== 0) {
return;
}
$rx = substr($xx, $lz);
$s2 = $ex . str_replace("\\", "/", $rx) . ".php";
if (file_exists($s2)) {
require $s2;
}
}
function td()
{
return [
"TOC" => "Contents",
"WORD" => "Word",
"FULLTEXT_INDEX" => "Fulltext",
"KEYWORD_INDEX" => "Keyword",
"KEYWORD_MULTIPLE_INDEX" => "KeywordMultiple",
];
}
function jd(AeDatabaseConfiguration $databaseConfiguration)
{
static $ao = null;
if ($ao === null and SEARCH_USE_ROSE) {
$qo = new \PDO(
"mysql:" .
"host=" .
$databaseConfiguration->host .
";" .
"dbname=" .
$databaseConfiguration->name .
";" .
"port=" .
$databaseConfiguration->port,
$databaseConfiguration->user,
ks($databaseConfiguration->password)
);
$qo->exec("SET NAMES utf8mb4");
$qo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$lo = td();
$ao = new PdoStorage(
$qo,
$databaseConfiguration->getPrefix() . SEARCH_EXTRA_PREFIX,
[
MysqlRepository::TOC => $lo["TOC"],
MysqlRepository::WORD => $lo["WORD"],
MysqlRepository::FULLTEXT_INDEX => $lo["FULLTEXT_INDEX"],
MysqlRepository::KEYWORD_INDEX => $lo["KEYWORD_INDEX"],
MysqlRepository::KEYWORD_MULTIPLE_INDEX =>
$lo["KEYWORD_MULTIPLE_INDEX"],
]
);
}
return $ao;
}
function hd($e1, $o9)
{
foreach ($o9 as $gh) {
if ($gh == "-") {
continue;
}
$gh = preg_quote($gh, "/");
$gh = str_replace("", "[]", $gh);
$gh = str_replace("", "[]", $gh);
$e1 = preg_replace(
"/(?<=^|\W)(" . $gh . "[\w\p{M}]*)/iu",
'<mark>$1</mark>',
$e1
);
}
$e1 = str_replace("</mark><mark>", " ", $e1);
$e1 = str_replace("</mark> <mark>", " ", $e1);
return $e1;
}
function gd($zo)
{
$ko = mb_strtoupper(mb_substr($zo, 0, 1));
return $ko . mb_substr($zo, 1);
}
function wd(AeDatabaseConfiguration $databaseConfiguration, $xo = false)
{
$eo = false;
if ($databaseConfiguration->hasSubsetSpecified() and !$eo) {
if (Log::$a) {
__log("Search: unmark and unindex subset");
}
$m1 = "WHERE `SubsetID`=" . $databaseConfiguration->getSubset();
} else {
if (Log::$a) {
__log("Search: unmark and unindex all");
}
$m1 = "";
}
sm(
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"SET `IsIndexed`=0 " .
$m1,
"mark all notes for reindexing"
);
if ($xo) {
hb("Notes marked for reindexing", E2E_MESSAGE);
}
$mt = jd($databaseConfiguration);
try {
$mt->erase();
if ($xo) {
hb("Indexes erased", E2E_MESSAGE);
}
} catch (\S2\Rose\Exception\RuntimeException $e) {
if (Log::$a) {
__log("Rose threw RuntimeException");
}
}
}
function e2m_password_reset()
{
global $_strings, $_config, $settings;
if (!is_file(USER_DIR . "password-reset.psa")) {
$yn = sha1(as_());
$url = eq("e2m_password", ["recovery-key" => $yn]);
@e3(USER_DIR . "password-reset.psa", $url);
}
$vb["title"] = $_strings["pt--password-reset"];
$vb["heading"] = $_strings["pt--password-reset"];
$ro = (bool) ($sa = $settings["author_email"]);
$vb["form"] = "form-password-reset-email";
$vb["form-password-reset-email"] = [
"form-action" => eq("e2s_password_reset_email"),
"show-controls?" => $ro,
"submit-text" => $_strings["fb--send-link-by-email"],
];
if ($_config["user_has_access_to_filesystem"]) {
$vb["form-password-reset-email"]["reset-info"] =
$_strings["gs--password-reset-link-saved"];
} elseif (!$ro) {
hb($_strings["er--cannot-reset-password"]);
}
return $vb;
}
function e2s_password_reset_email()
{
global $_strings, $settings;
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1();
}
if (array_key_exists("email", $_POST)) {
$js = trim($_POST["email"]);
}
if (!$js) {
hb($_strings["er--cannot-send-link-email-empty"]);
z1(eq("e2m_password_reset"));
}
$to = @file_get_contents(USER_DIR . "password-reset.psa");
if (strlen($to) == 0) {
hb($_strings["er--error-occurred"]);
z1(eq("e2m_password_reset"));
}
if ($sa = $settings["author_email"]) {
if ($js == $sa) {
$fa = kn("password-reset", ["reset-href" => $to]);
$da = $_strings["em--password-reset-subject"];
$aa = "From: " . xn();
en($sa, $da, $fa, $aa);
}
hb($_strings["gs--password-reset-link-sent-maybe"], E2E_MESSAGE);
z1(eq("e2m_password_reset"));
}
die();
}
function e2m_password($parameters)
{
global $_strings;
$jo = false;
$yn = "";
if (array_key_exists("recovery-key", $parameters)) {
$yn = $parameters["recovery-key"];
$url = eq("e2m_password", ["recovery-key" => $yn]);
$to = @file_get_contents(USER_DIR . "password-reset.psa");
if (strlen($to) > 0) {
$jo = $url == $to;
}
}
if (ys() or $jo) {
$vb["title"] = $_strings["pt--password"];
$vb["heading"] = $_strings["pt--password-for-blog"];
if ($jo) {
$vb["title"] = $_strings["pt--password-reset"];
$vb["heading"] = $_strings["pt--password-reset"];
}
$vb["form"] = "form-password";
$vb["form-password"] = [
".recovery-key" => $yn,
"form-action" => eq("e2s_password_save"),
"recovering?" => $jo,
"submit-text" => $_strings["fb--change"],
];
return $vb;
} else {
z1();
}
}
function e2m_sessions()
{
global $_strings;
$st = ns();
$vb["title"] = $_strings["pt--sessions"];
$vb["heading"] = $_strings["pt--sessions"];
$ho = [];
$yn = $_COOKIE[x1("key")];
foreach ($st["sessions"] as $k3 => $x3) {
$ho[] = [
"current?" => sha1($yn) === $x3["key_hash"],
"opened" => [(int) $x3["stamp"], oa()],
"ip-address" => $x3["remote_ip"],
"source" =>
$x3["remote_ip"] == "127.0.0.1"
? $_strings["gs--locally"]
: $x3["remote_ip"],
"title" => ss($x3["ua"]),
"user-agent" => $x3["ua"] ? $x3["ua"] : $_strings["gs--unknown"],
];
}
$ho = array_reverse($ho);
$vb["sessions"]["each"] = $ho;
if (count($ho) > 1) {
$vb["form"] = "form-sessions";
$vb["form-sessions"] = [
"form-action" => eq("e2s_drop_other_sessions"),
"submit-text" => $_strings["fb--end-all-sessions-but-this"],
];
}
return $vb;
}
function e2m_sign_in()
{
global $_strings;
if (ys()) {
z1(eq("e2m_frontpage", ["page" => 1]));
}
return ["title" => $_strings["pt--sign-in"]];
}
function e2m_sign_out()
{
global $_strings;
$st = ns();
$go = -1;
if (array_key_exists("sessions", $st) and is_array($st["sessions"])) {
foreach ($st["sessions"] as $k3 => $x3) {
$yn = $_COOKIE[x1("key")];
if (sha1($yn) === $x3["key_hash"]) {
$go = $k3;
break;
}
}
}
if ($go > -1) {
unset($st["sessions"][$go]);
}
if (!ms($st)) {
hb($_strings["er--cannot-write-auth-data"], E2E_PERMISSIONS_ERROR);
}
e1("key", "");
z1();
}
function e2s_password_save()
{
global $_strings;
od();
$jo = false;
$wo = trim($_POST["old-password"]);
if ($yn = trim($_POST["recovery-key"])) {
$url = eq("e2m_password", ["recovery-key" => $yn]);
$to = @file_get_contents(USER_DIR . "password-reset.psa");
if (strlen($to) > 0) {
$jo = $url == $to;
}
}
if (cs($wo) or $jo) {
$ft = trim($_POST["new-password"]);
if ($ft != "") {
if (@e3(USER_DIR . "password-hash.psa", serialize(sha1($ft)))) {
@unlink(USER_DIR . "password-reset.psa");
hb($_strings["gs--password-changed"], E2E_MESSAGE);
z1();
} else {
hb(
$_strings["er--could-not-change-password"],
E2E_PERMISSIONS_ERROR
);
z1(eq("e2m_password", ["recovery-key" => ""]));
}
} else {
hb($_strings["er--no-password-entered"], E2E_USER_ERROR);
z1(eq("e2m_password", ["recovery-key" => ""]));
}
} else {
hb($_strings["er--wrong-password"], E2E_USER_ERROR);
z1(eq("e2m_password", ["recovery-key" => ""]));
}
die();
}
function ud()
{
global $_token;
if (!ys()) {
return "";
}
return $_token;
}
function id()
{
return sha1(
$_SERVER["HTTP_USER_AGENT"] . pd() . time() . mt_rand(1000000, 9999999)
);
}
function od()
{
global $_token;
if (!ys()) {
return true;
}
if (
!array_key_exists("token", $_POST) or
(string) $_POST["token"] !== (string) @$_token
) {
throw new AeTokenException("Incorrect token");
}
return true;
}
function pd()
{
$uo = $_SERVER["REMOTE_ADDR"];
if (array_key_exists("HTTP_X_FORWARDED_FOR", $_SERVER)) {
$uo = array_pop(explode(",", $_SERVER["HTTP_X_FORWARDED_FOR"]));
}
return $uo;
}
function e2s_sign_in()
{
global $_strings;
$st = ns();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$password = @$_POST["password"];
$io = @$_POST["is_public_pc"];
} else {
$password = @$_GET["password"];
$io = false;
}
if (cs($password)) {
@unlink(USER_DIR . "password-reset.psa");
$oo = [
"stamp" => time(),
"remote_ip" => pd(),
"key_hash" => bs($io),
"anti_csrf_token" => id(),
"ua" => $_SERVER["HTTP_USER_AGENT"],
];
$st["sessions"][] = $oo;
} elseif (strlen(trim($password)) > 0) {
qs();
hb($_strings["er--wrong-password"], E2E_USER_ERROR);
}
if (!ms($st)) {
hb($_strings["er--cannot-write-auth-data"], E2E_PERMISSIONS_ERROR);
z1();
}
k1();
}
function e2s_drop_other_sessions()
{
global $_strings;
od();
$st = ns();
$oo = null;
foreach ($st["sessions"] as $k3 => $x3) {
$yn = $_COOKIE[x1("key")];
if (sha1($yn) === $x3["key_hash"]) {
$oo = $x3;
break;
}
}
$st["sessions"] = [$oo];
if (!ms($st)) {
hb($_strings["er--cannot-write-auth-data"], E2E_PERMISSIONS_ERROR);
}
k1();
die();
}
function cs($password)
{
$po = @unserialize(file_get_contents(USER_DIR . "password-hash.psa"));
return sha1($password) === $po and trim($password) != "";
}
function vs()
{
$po = @unserialize(file_get_contents(USER_DIR . "password-hash.psa"));
return is_string($po) and $po !== "";
}
function bs($cp = false)
{
$yn = as_();
$vp = sha1($yn);
e1("key", $yn, !$cp);
return $vp;
}
function ys()
{
static $bp = null;
global $_token;
if ($bp !== null) {
return $bp;
}
$bp = false;
if (!isset($_COOKIE[x1("key")])) {
return $bp;
}
$st = ns();
$vp = sha1($_COOKIE[x1("key")]);
$bp = false;
$_token = "";
foreach ($st["sessions"] as &$oo) {
if ($vp === $oo["key_hash"]) {
$bp = true;
$_token = (string) @$oo["anti_csrf_token"];
if ($_token === "") {
$oo["anti_csrf_token"] = id();
ms($st);
}
break;
}
}
if (!$bp) {
e1("key", "");
}
return $bp;
}
function ns()
{
$st = [];
if (is_file(USER_DIR . "auth.psa")) {
$st = unserialize(@file_get_contents(USER_DIR . "auth.psa"));
}
if (!is_array($st)) {
$st = [];
}
if (!array_key_exists("sessions", $st)) {
$st["sessions"] = [];
}
if (!is_array($st["sessions"])) {
$st["sessions"] = [];
}
return $st;
}
function ms($st)
{
return e3(USER_DIR . "auth.psa", serialize($st));
}
function fs()
{
if ($yn = @$_COOKIE[x1("key")]) {
return x1("key") . "=" . $yn . "";
}
}
function ds()
{
if ($yn = @$_COOKIE[x1("key")]) {
return "Cookie: " . x1("key") . "=" . $yn . "\r\n";
}
return "\r\n";
}
function ss($yp)
{
global $_strings;
if (strstr($yp, "iPhone")) {
return $_strings["gs--ua-iphone"];
}
if (strstr($yp, "iPad")) {
return $_strings["gs--ua-ipad"];
}
if (strstr($yp, "Opera")) {
$vb = $_strings["gs--ua-opera"];
}
if (strstr($yp, "Firefox")) {
$vb = $_strings["gs--ua-firefox"];
}
if (strstr($yp, "Chrome")) {
$vb = $_strings["gs--ua-chrome"];
}
if (strstr($yp, "Safari") and !strstr($yp, "Chrome")) {
$vb = $_strings["gs--ua-safari"];
}
if (!$vb) {
$vb = $_strings["gs--ua-unknown"];
}
if (strstr($yp, "Macintosh")) {
if ($vb) {
$vb .= " " . $_strings["gs--ua-for-mac"];
}
}
return $vb;
}
function e2j_check_password()
{
$po = @unserialize(file_get_contents(USER_DIR . "password-hash.psa"));
$password = "";
if (array_key_exists("password", $_POST)) {
$password = $_POST["password"];
}
qs();
$dl = [
"success" => true,
"data" => [
"password-correct" =>
trim($password) !== "" and sha1($password) === $po,
],
];
$dl = json_encode($dl);
die($dl);
}
function as_()
{
if (function_exists("random_bytes")) {
$fp = sha1(random_bytes(128));
} else {
$fp = "";
$dp = "0123456789abcdef";
for ($gb = 0; $gb < 40; $gb++) {
$fp .= $dp[mt_rand(0, 15)];
}
$fp .= time() . microtime();
$fp = sha1($fp);
}
return $fp;
}
function qs()
{
if (is_file(USER_DIR . "password-wait.psa")) {
$sp = unserialize(file_get_contents(USER_DIR . "password-wait.psa"));
if ($sp["delay"] < 5) {
$sp["delay"]++;
}
if (time() - $sp["time"] > SECONDS_IN_A_MINUTE) {
$sp["delay"] = 0;
}
$sp["time"] = time();
} else {
$sp = ["time" => time(), "delay" => 5];
}
e3(USER_DIR . "password-wait.psa", serialize($sp));
sleep($sp["delay"]);
}
function ls()
{
static $ap;
if (empty($ap)) {
$ap = md5("seret");
}
return $ap;
}
function zs($m4)
{
$yn = ls();
$qp = strlen($yn);
$lp = strlen($m4);
$vb = "";
for ($gb = 0; $gb < $lp + rand(16, 64); ++$gb) {
if ($gb > $lp) {
$zp = rand(0, 127);
} elseif ($gb == $lp) {
$zp = 0;
} else {
$zp = ord($m4[$gb]);
}
$kp = chr(($zp + ord($yn[$gb % $qp])) % 256);
$vb .= $kp;
}
$vb = base64_encode($vb);
return $vb;
}
function ks($m4)
{
$yn = ls();
$qp = strlen($yn);
$m4 = base64_decode((string) @$m4);
$lp = strlen($m4);
$vb = "";
for ($gb = 0; $gb < $lp; ++$gb) {
$xp = (ord($m4[$gb]) + 256 - ord($yn[$gb % $qp])) % 256;
if ($xp === 0) {
break;
}
$vb .= chr($xp);
}
return $vb;
}
function xs()
{
global $settings;
if (ys()) {
return null;
} else {
return [
"form-action" => eq("e2s_sign_in"),
"form-check-password-action" => eq("e2j_check_password"),
"login-name" => @$settings["author"],
"public-pc?" => false,
"reset-href" => eq("e2m_password_reset"),
];
}
}
function es()
{
if (!ys()) {
return;
}
list(, $ep) = ts();
$h3 = false;
foreach ($ep as $od => $rp) {
if (Log::$a) {
__log(
'Selfcheck: Double-checking remote access of "' .
$od .
'" ' .
"before showing a warning (status was " .
$rp .
")..."
);
}
$m2 = vv(AeEnv::$p . $od);
if ($m2 and $m2["http_code"] >= 400) {
continue;
}
$h3 = true;
$url = AeEnv::$p . $od;
hb(
'Securityalert: <a href="' .
$url .
'">' .
$od .
"</a> " .
"responded withHTTP" .
$m2["http_code"] .
" insteadof403"
);
}
return $h3;
}
function rs()
{
list($tp, $ep) = ts();
$xd = time();
if (
$tp === false or
array_key_exists("completed-stamp", $tp) and
@$tp["completed-stamp"] < $xd - SECONDS_IN_A_WEEK
) {
$tp = js();
}
$jp = false;
if (count($ep)) {
$jp = true;
}
foreach ($tp["statuses"] as $od => $rp) {
if ($rp >= 400) {
continue;
}
if (Log::$a) {
__log('Selfcheck: Checking remote access of "' . $od . '"...');
}
$m2 = vv(AeEnv::$p . $od);
if (!$m2 or @$m2["http_code"] < 200) {
break;
}
$rp = $m2["http_code"];
$tp["statuses"][$od] = $rp;
if (Log::$a) {
__log("Selfcheck: The response is " . $m2["http_code"]);
}
if ($rp >= 400 and !$jp) {
break;
} else {
$jp = true;
}
}
if (!array_key_exists("completed-stamp", $tp)) {
end($tp["statuses"]);
$hp = !empty(current($tp["statuses"]));
if ($hp) {
$tp["completed-stamp"] = $xd;
}
if ($hp) {
$tp["completed"] = date("r", $xd);
}
}
@e3(USER_DIR . "checklist.psa", serialize($tp));
}
function ts()
{
static $tp,
$ep = null;
if ($tp !== null and $ep !== null) {
return [$tp, $ep];
}
$gp = USER_DIR . "checklist.psa";
$tp = @unserialize(file_get_contents($gp));
$wp = @$tp["statuses"];
$ep = [];
if (is_array($wp)) {
foreach ($wp as $od => $rp) {
if ($rp !== null and $rp < 400) {
$ep[$od] = $rp;
}
}
} else {
$tp = false;
}
return [$tp, $ep];
}
function js()
{
global $_config;
if (Log::$a) {
__log("Selfcheck: Reset access checklist file");
}
$up = array_merge(
AeFileManager::writtenFiles(
$_config["path_user"],
$_config["path_media"]
),
[
".htaccess",
"system/core.php",
"system/default/config.php",
INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME,
$_config["path_media"] . PICTURES_DIRNAME . ".htaccess",
$_config["path_media"] . THUMBNAILS_DIRNAME . ".htaccess",
$_config["path_media"] . AVATARS_DIRNAME . ".htaccess",
$_config["path_media"] . USERPIC_DIRNAME . ".htaccess",
$_config["path_media"] . VIDEO_DIRNAME . ".htaccess",
$_config["path_media"] . AUDIO_DIRNAME . ".htaccess",
USER_DIR . CACHE_FILENAME_FRONTPAGE,
USER_DIR . BACKUP_DIRNAME . "backup-tail.sql",
]
);
foreach ($up as $od) {
$ip[$od] = null;
}
$tp = ["statuses" => $ip];
@e3(USER_DIR . "checklist.psa", serialize($tp));
return $tp;
}
function hs()
{
$op["items_count"] = 0;
$op["total_count"] = 0;
$op["percentage"] = 0;
$op["stamp_completed"] = false;
$gp = USER_DIR . "checklist.psa";
$tp = @unserialize(file_get_contents($gp));
if ($tp === false) {
return $op;
}
$wp = @$tp["statuses"];
$g2 = $pp = 0;
if (is_array($wp)) {
foreach ($wp as $rp) {
$g2++;
if ($rp !== null) {
$pp++;
}
}
$op["items_count"] = $pp;
$op["total_count"] = $g2;
$op["percentage"] = j1($pp, $g2);
}
$op["stamp_completed"] = @$tp["completed-stamp"];
return $op;
}
function e2_load_settings_from_user_folder_($ccv)
{
$vcv = [];
if (is_file($ccv . "settings.json")) {
$vcv = json_decode(file_get_contents($ccv . "settings.json"), true);
}
$vcv = is($vcv);
return $vcv;
}
function e2m_settings()
{
global $_lang, $_template, $_strings, $_config, $settings;
$bcv = [];
foreach (glob(SYSTEM_DIR . LANGUAGES_DIRNAME . "*.php") as $od) {
$ycv = substr(basename($od), 0, 2);
$ncv = file_get_contents($od);
if (
preg_match('/^ *\/\/ *display_name *\= *(.*?) *$/ismu', $ncv, $v6)
) {
$y0 = $v6[1];
} else {
$y0 = $ycv;
}
$bcv[$ycv] = [
"selected?" => (bool) ($_lang == $ycv),
"display-name" => $y0,
];
}
$kd = $mcv = false;
$fcv = (string) @$kd["pay-href"];
if ((string) $fcv === "") {
$fcv = "https://" . $_strings["e2--website-host"] . "/get/";
}
if (!isset($_template)) {
kf();
}
$vb["title"] = $_strings["pt--settings"];
$vb["heading"] = $_strings["pt--settings"];
$vb["form"] = "form-preferences";
$vb["form-preferences"] = [
"blog-title-default" => htmlspecialchars(
(string) @$_strings["e2--default-blog-title"],
ENT_COMPAT,
"UTF-8"
),
"blog-title" => htmlspecialchars(ev(), ENT_COMPAT, "UTF-8"),
"blog-subtitle" => htmlspecialchars(
(string) @$settings["blog_subtitle"],
ENT_COMPAT,
"UTF-8"
),
"blog-meta-description" => htmlspecialchars(
(string) @$settings["meta_description"],
ENT_COMPAT,
"UTF-8"
),
"blog-author-default" => htmlspecialchars(
(string) @$_strings["e2--default-blog-author"],
ENT_COMPAT,
"UTF-8"
),
"blog-author" => htmlspecialchars(
(string) @$settings["author"],
ENT_COMPAT,
"UTF-8"
),
"languages" => $bcv,
"language" => $_lang,
"form-action" => eq("e2s_settings_save"),
"userpic-href" => tv("square"),
"notes-per-page" => $settings["appearance"]["notes_per_page"],
"emailing-possible?" => MAIL_ENABLED,
"email-notify?" => (bool) @$settings["notifications"]["new_comments"],
"email" => htmlspecialchars(
(string) @$settings["author_email"],
ENT_COMPAT,
"UTF-8"
),
"comments-default-on?" => (bool) @$settings["comments"]["default_on"],
"comments-require-gip?" => (bool) @$settings["comments"]["require_gip"],
"comments-fresh-only?" => (bool) @$settings["comments"]["fresh_only"],
"show-view-counts?" => (bool) @$settings["appearance"][
"show_view_counts"
],
"show-sharing-buttons?" => (bool) @$settings["appearance"][
"show_sharing_buttons"
],
"includes-main-menu-fields?" => false,
"main-menu-promo" => e2l_get_string("pm--main-menu", [
"url" => $_config["paid_features_url"],
]),
"show-main-menu?" => false,
"main-menu-items" => [],
"includes-analytics-fields?" => false,
"analytics-promo" => e2l_get_string("pm--analytics", [
"url" => $_config["paid_features_url"],
]),
"template-name" => $_template["name"],
"templates" => of(),
"respond-to-dark-mode?" => (bool) @$settings["appearance"][
"respond_to_dark_mode"
],
"submit-text" => $_strings["fb--save-changes"],
"show-payment-info?" => $mcv and $kd !== false,
"paid-period" => @$kd["licensed?"]
? time() <= $kd["until-stamp"]
: false,
"paid-period-ended" => @$kd["licensed?"]
? time() > $kd["until-stamp"]
: false,
"paid-until" => @$kd["licensed?"] ? [$kd["until-stamp"], pa()] : false,
"pay-href" => $fcv,
"space-usage" => yy(vy(), true),
];
return $vb;
}
function e2s_settings_save()
{
global $settings, $_strings;
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_settings"));
}
od();
$acv = $zd = "";
if (array_key_exists("blog-title", $_POST)) {
$acv = trim($_POST["blog-title"]);
}
if (array_key_exists("blog-subtitle", $_POST)) {
$zd = trim($_POST["blog-subtitle"]);
}
if (array_key_exists("blog-meta-description", $_POST)) {
$qcv = trim($_POST["blog-meta-description"]);
}
if (array_key_exists("blog-author", $_POST)) {
$lcv = trim($_POST["blog-author"]);
}
if (array_key_exists("language", $_POST)) {
$zcv = $_POST["language"];
}
if (array_key_exists("email", $_POST)) {
$js = trim($_POST["email"]);
}
$kcv = (int) $_POST["notes-per-page"];
$settings["blog_title"] = $acv;
$settings["blog_title"] = ev();
$settings["author"] = $lcv;
$settings["author_email"] = $js;
$settings["notifications"]["new_comments"] = isset($_POST["email-notify"]);
if (array_key_exists("template", $_POST)) {
$settings["template"] = trim($_POST["template"]);
}
$settings["comments"]["default_on"] = isset($_POST["comments-default-on"]);
$settings["comments"]["require_gip"] = isset(
$_POST["comments-require-gip"]
);
$settings["appearance"]["show_view_counts"] = isset(
$_POST["show-view-counts"]
);
if (
!array_key_exists("language", $settings) or
$settings["language"] != $zcv
) {
e2_drop_all_kinds_of_cache();
$settings["language"] = $zcv;
}
if (
@$settings["blog_subtitle"] != $zd or
@$settings["meta_description"] != $qcv or
@$settings["appearance"]["notes_per_page"] != $kcv or
@$settings["appearance"]["show_sharing_buttons"] !=
isset($_POST["show-sharing-buttons"]) or
@$settings["appearance"]["respond_to_dark_mode"] !=
isset($_POST["respond-to-dark-mode"]) or
@$settings["comments"]["fresh_only"] !=
isset($_POST["comments-fresh-only"])
) {
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE_FEED);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE_AUTHOR);
$settings["blog_subtitle"] = $zd;
$settings["meta_description"] = $qcv;
$settings["appearance"]["notes_per_page"] = $kcv;
$settings["appearance"]["show_sharing_buttons"] = isset(
$_POST["show-sharing-buttons"]
);
$settings["appearance"]["respond_to_dark_mode"] = isset(
$_POST["respond-to-dark-mode"]
);
$settings["comments"]["fresh_only"] = isset(
$_POST["comments-fresh-only"]
);
}
bq(USER_DIR . CACHE_FILENAMES_NOTES_COMMENTS);
if (
!@e3(USER_DIR . "settings.json", json_encode($settings, E2_JSON_STYLE))
) {
hb($_strings["er--settings-not-saved"], E2E_PERMISSIONS_ERROR);
z1(eq("e2m_settings"));
}
z1(eq("e2m_frontpage", ["page" => 1]));
}
function e2m_underhood()
{
global $_db, $_config;
if (!$_config["allow_underhood_access"]) {
return e2m_error404();
}
$vb["title"] = "Underhood";
$vb["heading"] = "Underhood";
$xcv = $_SERVER["SERVER_SOFTWARE"];
if (preg_match("/^Apache\/([0-9.]+)\b/i", $xcv, $v6)) {
$xcv = "Apache " . $v6[1];
} elseif (preg_match("/^nginx\/([0-9.]+)\b/i", $xcv, $v6)) {
$xcv = "Nginx " . $v6[1];
}
dm(bl(), "check version");
$fw = pa();
$ecv = $rcv = 0;
foreach (glob(USER_DIR . CACHES_DIRNAME . "*") as $od) {
$ecv++;
$rcv += stat($od)["size"];
}
$tcv = $jcv = 0;
foreach (glob(INSTANCE_DIR . LOGS_DIRNAME . "*") as $od) {
$tcv++;
$jcv += stat($od)["size"];
}
$fo = qd();
$hcv = j1($fo["indexed_count"], $fo["total_count"]);
$gcv = false;
if ($fo["time_spent"]) {
if (is_numeric($fo["time_spent"])) {
$gcv = floor($fo["time_spent"]);
}
if ($gcv >= 60) {
$gcv =
floor($gcv / 60) .
"min " .
str_pad($gcv % 60, 2, "0", STR_PAD_LEFT) .
"s";
} elseif ($gcv > 0) {
$gcv .= "s";
} else {
$gcv = false;
}
}
$op = hs();
$wcv = array_keys(km(USER_DIR . BACKUP_DIRNAME));
$vb["form"] = "form-underhood";
$vb["form-underhood"] = [
"server-software" => $xcv,
"db-software" => $_db["software"],
"db-version" => $_db["version"],
"form-action-engine-rebuild" => BUILT
? false
: eq("e2s_post_service", ["service" => "build"]),
"current-timezone-offset" => ga($fw["offset"]),
"current-timezone-is-dst" => $fw["is_dst"],
"cache-files-count" => $ecv,
"cache-files-size" => $rcv,
"form-action-cache-invalidate" => eq("e2s_post_service", [
"service" => "sync",
]),
"search-index-items-count" => $fo["indexed_count"],
"search-index-total-items-count" => $fo["total_count"],
"search-index-time-spent" => $gcv,
"search-index-percentage" => $hcv,
"form-action-search-index-continue" => kd()
? false
: eq("e2s_bsi_step"),
"form-action-search-index-rebuild" => eq("e2s_reindex"),
"checklist-items-count" => $op["items_count"],
"checklist-total-items-count" => $op["total_count"],
"checklist-percentage" => $op["percentage"],
"checklist-stamp-completed" => !empty($op["stamp_completed"])
? n1('D, M d, Y \a\t H:i:s', $op["stamp_completed"])
: false,
"form-action-checklist-reset" => eq("e2s_post_service", [
"service" => "checklist-reset",
]),
"log-files-count" => $tcv,
"log-files-size" => $jcv,
"form-action-logs-enable" => is_file(
INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME
)
? ""
: eq("e2s_post_service", ["service" => "log"]),
"form-action-logs-erase-disable" => $tcv
? eq("e2s_post_service", ["service" => "unlog"])
: "",
"backup-last" => count($wcv)
? n1('D, M d, Y \a\t H:i:s', $wcv[0])
: false,
"form-action-backup" => eq("e2s_dump"),
"form-action-database-migrate" => eq("e2s_post_service", [
"service" => "migrate",
]),
"form-action-license-verify" => eq("e2s_post_service", [
"service" => "verify",
]),
];
return $vb;
}
function e2m_database()
{
global $settings, $_strings, $_config;
$databaseConfiguration = bl();
if (
$databaseConfiguration->source !== "settings" or
!$_config["allow_db_config"]
) {
return e2m_error404();
}
$vb["title"] = $_strings["pt--database"];
$vb["heading"] = $_strings["pt--database"];
$vb["form"] = "form-database";
$vb["form-database"] = [
"form-action" => eq("e2s_database_save"),
"db-server" => htmlspecialchars(
@$settings["db"]["server"] ? $settings["db"]["server"] : "localhost"
),
"db-user" => htmlspecialchars(
@$settings["db"]["user_name"]
? $settings["db"]["user_name"]
: "root"
),
"db-database" => htmlspecialchars(@$settings["db"]["name"]),
"submit-text" => $_strings["fb--connect-to-this-db"],
];
return $vb;
}
function ws($backup_dir, $ucv, $prefix = null, $subset = null)
{
$icv["server"] = $icv["user_name"] = $icv["passw"] = $icv["name"] = "";
if (array_key_exists("db-server", $ucv)) {
$icv["server"] = $ucv["db-server"];
}
if (array_key_exists("db-user", $ucv)) {
$icv["user_name"] = $ucv["db-user"];
}
if (array_key_exists("db-password", $ucv)) {
$icv["passw"] = $ucv["db-password"];
}
if (array_key_exists("db-database", $ucv)) {
$icv["name"] = $ucv["db-database"];
}
$databaseConfiguration = new AeDatabaseConfiguration(
"post",
$backup_dir,
$icv["server"],
$icv["user_name"],
zs($icv["passw"]),
$icv["name"],
$prefix,
$subset
);
return $databaseConfiguration;
}
function e2s_database_save()
{
global $settings, $_db, $_strings, $_config;
od();
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_database"));
}
$databaseConfiguration = bl();
if (
$databaseConfiguration->source !== "settings" or
!$_config["allow_db_config"]
) {
return e2m_error404();
}
$ucv = $_POST;
if (!array_key_exists("db-password", $ucv)) {
$ucv["db-password"] = htmlspecialchars(ks(@$settings["db"]["passw"]));
}
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$ucv,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
$dt = false;
try {
dm($databaseConfiguration, "check database from HTTP post");
$yt = pn($databaseConfiguration);
if (!$yt["occupied"] or !$yt["migrateable"]) {
hb($_strings["er--db-data-incomplete"]);
z1(eq("e2m_database"));
}
wn($databaseConfiguration);
$dt = true;
} catch (AeMySQLCannotConnectException $e) {
hb(
$_strings["er--cannot-connect-to-db"] .
":<br />" .
mysqli_connect_error() .
" (" .
mysqli_connect_errno() .
")"
);
} catch (AeMySQLTooOldException $e) {
hb(
e2l_get_string("er--dbs-version-too-old", [
"dbs" => $_db["software"],
"v1" => $_db["version"],
"v2" => $_db["version-minimum"],
])
);
} catch (AeMySQLException $e) {
hb(
$_strings["er--cannot-find-db"] . " " . $databaseConfiguration->name
);
}
if (!$dt) {
z1(eq("e2m_database"));
}
$settings["db"] = $databaseConfiguration->getDatabaseParamsArray();
if (
!@e3(USER_DIR . "settings.json", json_encode($settings, E2_JSON_STYLE))
) {
hb($_strings["er--settings-not-saved"], E2E_PERMISSIONS_ERROR);
z1(eq("e2m_database"));
}
e2_drop_all_kinds_of_cache();
if (!$_config["retain_search_indexes_on_db_switch"]) {
$mt = jd(bl());
try {
$mt->erase();
} catch (\S2\Rose\Exception\RuntimeException $e) {
if (Log::$a) {
__log("Rose not available");
}
}
ld(USER_DIR);
}
vv(eq("e2s_bsi_step"));
z1(eq("e2m_settings"));
}
function us()
{
return class_exists("ZipArchive");
}
function e2m_get_backup()
{
if (us()) {
$ocv = new ZipArchive();
$pcv = USER_DIR . BACKUP_DIRNAME . "backup.zip";
if ($ocv->open($pcv, ZIPARCHIVE::CREATE)) {
@$ocv->addEmptyDir("backup");
$cvv = USER_DIR . BACKUP_DIRNAME . "backup-tail.sql";
$vvv = "";
$bvv = -1;
foreach (glob(USER_DIR . BACKUP_DIRNAME . "backup-*.sql") as $s2) {
if ($s2 === $cvv) {
continue;
}
$yvv = stat($s2);
if ($yvv["ctime"] > $bvv) {
$vvv = $s2;
}
$bvv = $yvv["ctime"];
}
if ($vvv === "") {
$vvv = rm(bl());
}
$ocv->addFile($vvv, "backup/" . basename($vvv));
if (is_file($cvv)) {
@file_put_contents(
$cvv,
"COMMIT;\r\n\r\n",
FILE_APPEND | LOCK_EX
);
@chmod($cvv, E2_NEW_FILES_RIGHTS);
}
$ocv->addFile($cvv, "backup/backup-tail.sql");
$ocv->close();
}
if (is_file($pcv)) {
header("Content-Type: application/zip");
header('Content-Disposition: attachment; filename="backup.zip"');
readfile($pcv);
unlink($pcv);
} else {
die("Cannot get backup");
}
die();
} else {
die("Cannot get backup");
}
}
function is($vcv)
{
if (
!array_key_exists("appearance", $vcv) or
!array_key_exists("notes_per_page", $vcv["appearance"]) or
!is_numeric($vcv["appearance"]["notes_per_page"]) or
$vcv["appearance"]["notes_per_page"] < 1
) {
$vcv["appearance"]["notes_per_page"] = DEFAULT_ITEMS_PER_PAGE;
}
if ($vcv["appearance"]["notes_per_page"] > MAX_ITEMS_PER_PAGE) {
$vcv["appearance"]["notes_per_page"] = MAX_ITEMS_PER_PAGE;
}
if (
!array_key_exists("comments", $vcv) or
!array_key_exists("default_on", $vcv["comments"])
) {
$vcv["comments"]["default_on"] = false;
}
if (!array_key_exists("respond_to_dark_mode", $vcv["appearance"])) {
$vcv["appearance"]["respond_to_dark_mode"] = true;
}
if (
!array_key_exists("template", $vcv) or
(string) $vcv["template"] === ""
) {
$vcv["template"] = DEFAULT_TEMPLATE;
}
if (isset($vcv["description"])) {
if (!isset($vcv["blog_subtitle"])) {
$vcv["blog_subtitle"] = $vcv["description"];
}
unset($vcv["description"]);
}
if (isset($vcv["site_title"])) {
if (!isset($vcv["blog_title"])) {
$vcv["blog_title"] = $vcv["site_title"];
}
unset($vcv["site_title"]);
}
if (isset($vcv["user"])) {
if (!isset($vcv["author_email"])) {
$vcv["author_email"] = (string) @$vcv["user"]["email"];
}
unset($vcv["user"]);
}
if (isset($vcv["v3223_rss_permalinks_before_stamp"])) {
unset($vcv["v3223_rss_permalinks_before_stamp"]);
}
return $vcv;
}
function e2j_save_menu_order()
{
global $settings;
$dl = ["success" => false];
if (is_array(@$_POST["order"])) {
$settings["menu_order"] = $_POST["order"];
if (
@e3(
USER_DIR . "settings.json",
json_encode($settings, E2_JSON_STYLE)
)
) {
$dl = ["success" => true];
}
}
$dl = json_encode($dl);
die($dl);
}
function os($m3)
{
global $_config;
$mvv = $_config["share_to"];
$fvv = "|twitter|facebook|vkontakte|telegram|linkedin|whatsapp|";
if (@$_config["share_to_twitter_via"]) {
$zb["twitter"]["via"] = $_config["share_to_twitter_via"];
}
if (count($m3) > 0) {
$dvv = $m3[0];
$fvv .= "pinterest|";
$zb["pinterest"]["media"] = $dvv;
}
$svv = [];
foreach (explode(",", $mvv) as $avv) {
$avv = trim($avv);
if ($avv == "vk") {
$avv = "vkontakte";
}
if (strstr($fvv, "|" . $avv . "|")) {
$svv[$avv]["share?"] = true;
if (is_array(@$zb[$avv]) and count($zb[$avv])) {
$svv[$avv]["data"] = $zb[$avv];
}
}
}
return $svv;
}
function ps($qvv, $zb = null)
{
if ($qvv === "generic") {
$lvv = $zb;
} else {
if (!is_file($zvv = SYSTEM_DIR . "stubs/" . $qvv . ".php")) {
throw new AeStubException(
'No stub found for the problem "' . $qvv . '"'
);
}
$lvv = include $zvv;
}
$kvv = false;
if (!empty($lvv["button"])) {
$kvv = true;
$xvv = eq("e2m_frontpage", ["page" => 1]);
$evv = $lvv["button"];
}
$vb = [
"stub-kind" => $qvv,
"title" => $lvv["heading"],
"heading" => $lvv["heading"],
"stub" => $lvv["text"],
];
if ($kvv) {
$vb += ["stub-button-href" => $xvv, "stub-button-text" => $evv];
}
return $vb;
}
function e2m_tags()
{
global $_strings;
AeMainMenuManager::$isTagsCurrent = true;
$vb["title"] = $_strings["pt--tags"];
$vb["heading"] = $_strings["pt--tags"];
$vb["tags"] = da([]);
$cg = sa(true);
if ($cg === null) {
$vb["unavailable?"] = true;
} else {
$vb["tags"]["each"] = $cg;
if (count($cg) == 0) {
$vb["nothing"] = $_strings["gs--no-tags"];
}
}
return $vb;
}
function e2m_tag($parameters = [])
{
global $settings, $_config, $_strings;
if (Log::$a) {
__log("Tag {");
}
$gn = ys();
$tagNotesView = new AePageableNotesView("e2m_tag", $parameters);
$tagNotesView->setPortionSize($settings["appearance"]["notes_per_page"]);
$tagNotesView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$tagNotesView->setWantPaging(true);
$tagNotesView->setWantNewCommentsCount($gn);
$tagNotesView->setWantReadHrefs($_config["count_reads"]);
$tagNotesView->setWantControls($gn and !@$_config["read_only"]);
$tagNotesView->setWantHiddenTags($gn);
if (array_key_exists("*tags", $parameters)) {
$rvv = $parameters["*tags"];
} elseif (array_key_exists("*tag", $parameters)) {
$rvv = [$parameters["*tag"]];
} else {
$rvv = [];
}
$jb = [];
foreach ($rvv as $wb) {
if ($gn or $wb["IsVisible"]) {
$jb[] = $wb;
}
}
$tvv = count($jb);
if ($tvv == 0 or $tvv < count($rvv)) {
return e2m_error404();
}
foreach ($jb as $wb) {
if ($wb) {
$jvv[] = "nk.`KeywordID`=" . $wb["ID"];
}
}
$x0 =
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"JOIN `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk " .
"ON nk.`NoteID` = n.`ID` " .
"WHERE n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (" .
implode(" OR ", $jvv) .
") " .
"AND IsPublished=1 " .
df($gn) .
"GROUP BY n.`ID` " .
"HAVING COUNT(*)>=" .
$tvv;
$tagNotesView->setSQLCountRequest(
"SELECT COUNT(*) Total FROM (SELECT 1 " . $x0 . ") _"
);
$tagNotesView->setLimitlessSQLRequest(
"SELECT n.*, COUNT(*) " . $x0 . " " . "ORDER BY n.`Stamp` DESC"
);
$hvv = [];
foreach ($jb as $wb) {
$hvv[] = $wb["Keyword"];
if ($tvv === 1) {
AeMainMenuManager::addCurrentTag($wb["Keyword"]);
} else {
AeMainMenuManager::addParentTag($wb["Keyword"]);
}
}
$tagNotesView->setHighlightedTags($hvv);
$il = "";
$mj["description"] = "";
$mj["summary"] = "";
$mj["visible?"] = true;
foreach ($jb as $wb) {
if (!$wb["IsVisible"]) {
$mj["visible?"] = false;
break;
}
}
if ($tvv === 1) {
$gvv = $jb[0];
$wvv = b()["t" . $gvv["ID"]];
if (CACHE_TAG and $tagNotesView->isFirstPage()) {
if ($gn) {
$tagNotesView->setCacheFilename(
e2_cache_filename_with_id_(
$gvv["ID"],
USER_DIR . CACHE_FILENAMES_TAG_AUTHOR
)
);
} else {
$tagNotesView->setCacheFilename(
e2_cache_filename_with_id_(
$gvv["ID"],
USER_DIR . CACHE_FILENAMES_TAG
)
);
}
}
$u9 = ma($gvv["ID"], 5);
if ($gn) {
$mj["edit-href"] = eq("e2m_tag_edit", ["tag-alias" => $wvv]);
$uvv = (bool) $gvv["IsFavourite"];
$ivv = $parameters;
$ivv["flag"] = "IsFavourite";
$ivv["value"] = (int) !$uvv;
$mj["pinned?"] = false;
}
if ((string) $gvv["Description"] !== "") {
$ld = zy($gvv["Description"], "full");
$bq = $ld["text-final"];
$mj["description"] = $bq;
$mj["description-format-info"] = $ld["meta"];
m2(@$ld["meta"]["links-required"]);
}
if ((string) $gvv["Summary"] !== "") {
$mj["summary"] = ay(
htmlspecialchars($gvv["Summary"], ENT_NOQUOTES, "UTF-8")
);
} elseif ((string) $mj["description"] !== "") {
$mj["summary"] = mf($mj["description"]);
}
$ovv = eq("e2m_tag_rss", ["tag-alias" => $wvv]);
$pvv = eq("e2m_tag_json", ["tag-alias" => $wvv]);
d3("rss", ev() . ": " . $gvv["Keyword"], $ovv);
d3("json", ev() . ": " . $gvv["Keyword"], $pvv);
$mj["og-images"] = t3(
k2(
@$mj["description-format-info"]["resources-detected"],
g3("tag", $gvv["ID"])
)
);
$mj["name"] = htmlspecialchars($gvv["Keyword"], ENT_COMPAT, "UTF-8");
$mj["related"] = $u9;
$il = htmlspecialchars($gvv["PageTitle"], ENT_COMPAT, "UTF-8");
}
$g2 = $tagNotesView->getTotalNotes();
$mj["notes-count"] = $g2;
$mj["notes-count-text"] = e2l_get_string("pt--n-posts", ["number" => $g2]);
$cbv = $mj["notes-count-text"] . " " . $_strings["gs--tagged"];
$vbv = [];
foreach ($jb as $x3) {
$vbv[] = htmlspecialchars($x3["Keyword"], ENT_COMPAT, "UTF-8");
}
$vbv = implode(", ", $vbv);
if ((string) $il !== "") {
$ss = $il;
$as_ = $il;
} else {
$ss = ev() . ": " . $cbv . " " . $vbv;
if ($tvv > 1) {
$as_ = $_strings["pt--tags"] . ": " . $vbv;
} else {
$as_ = $_strings["pt--tag"] . ": " . $vbv;
}
}
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$z3 = da($parameters);
$vb = [
"title" => $ss,
"heading" => htmlspecialchars_decode($as_, ENT_COMPAT),
"notes" => $tagNotesView->getNotesCTree(),
"pages" => $tagNotesView->getPagesCTree(),
"tag" => $mj,
"tags" => $z3,
];
if (
!$tagNotesView->isExistingPage() and
!$tagNotesView->isFirstPageOfEmptyView()
) {
return e2m_error404();
}
if ($tagNotesView->isFirstPageOfEmptyView() and !$gn) {
return e2m_error404();
}
if ($tagNotesView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
if ((string) $mj["summary"] !== "") {
$vb["summary"] = $mj["summary"];
}
if ($tvv == 1) {
if (ys()) {
$vb["related-edit-href"] = $mj["edit-href"];
$vb["related-edit-title"] = $_strings["tt--edit-tag"];
}
}
if (Log::$a) {
__log("} // Tag");
}
return $vb;
}
function e2m_tag_edit($parameters = [])
{
global $_strings;
if (array_key_exists("*tag", $parameters)) {
$wb = $parameters["*tag"];
}
if (!@$wb) {
return e2m_error404();
}
AeMainMenuManager::addParentTag($wb["Keyword"]);
$v3 = qy("neasden", $wb["Description"]);
($y3 = @unserialize($wb["Uploads"])) or ($y3 = []);
$dg = e2_(l2(k2($v3, $y3)));
i3("Keywords", $wb, $v3);
$yk = vy();
$ybv = b()["t" . $wb["ID"]];
$nbv = [
"enabled?" => by($yk),
"each" => $dg,
"default-name" => htmlspecialchars($ybv, ENT_COMPAT, "UTF-8"),
"upload-action" => eq("e2j_file_upload"),
"rename-action" => eq("e2j_file_rename"),
"remove-action" => eq("e2j_file_remove"),
];
$mbv = [
".tag-id" => $wb["ID"],
".formatter-id" => "neasden",
"form-action" => eq("e2s_tag_edit"),
"submit-text" => $_strings["fb--save-changes"],
"tag-dotted" => ka($wb),
"page-title" => htmlspecialchars($wb["PageTitle"], ENT_COMPAT, "UTF-8"),
"page-title-placeholder" => htmlspecialchars(
$wb["Keyword"],
ENT_COMPAT,
"UTF-8"
),
"alias" => htmlspecialchars($ybv, ENT_COMPAT, "UTF-8"),
"description" => htmlspecialchars(
$wb["Description"],
ENT_COMPAT,
"UTF-8"
),
"summary" => (string) $wb["Summary"],
"pinned?" => (bool) $wb["IsFavourite"],
"space-usage" => yy($yk),
];
$vb = [
"body-uploads-enabled?" => by($yk),
"title" => $_strings["pt--tag-edit"] . ": " . $wb["Keyword"],
"heading" => $_strings["pt--tag-edit"],
"form" => "form-tag",
"form-tag" => $mbv,
"uploads" => $nbv,
"related-delete-href" => eq("e2m_tag_delete", ["*tag" => $wb]),
];
return $vb;
}
function e2s_tag_flag_ajax($parameters)
{
g1([
"flag-name" => "tag",
"candy-name" => "e2s_tag_flag_ajax",
"parameters" => $parameters,
"flipping-function" => function () use ($parameters) {
ca($parameters);
},
"redirect-candy" => "e2m_tag",
]);
}
function ca($parameters)
{
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_tag", $parameters));
}
od();
if (array_key_exists("*tag", $parameters)) {
$wb = $parameters["*tag"];
}
if (!$wb) {
throw new AeException("Tag record not cound from parameters");
}
e2_drop_caches_for_tag_($wb["ID"]);
fm(bl(), "Keywords", [
"ID" => $wb["ID"],
$parameters["flag"] => (int) ($parameters["value"] == 1),
]);
}
function e2m_tag_delete($parameters = [])
{
global $_strings;
if (array_key_exists("*tag", $parameters)) {
$fbv = $parameters["*tag"];
}
if (!$fbv) {
return e2m_error404();
}
$dbv = [
".tag-id" => $fbv["ID"],
"caution-text" => e2l_get_string(
"gs--tag-will-be-deleted-notes-remain",
["tag" => htmlspecialchars($fbv["Keyword"], ENT_COMPAT, "UTF-8")]
),
"tag" => htmlspecialchars($fbv["Keyword"], ENT_COMPAT, "UTF-8"),
"form-action" => eq("e2s_tag_delete"),
"submit-text" => $_strings["fb--delete"],
];
$vb = [
"title" => $_strings["pt--tag-delete"] . ": " . $fbv["Keyword"],
"heading" => $_strings["pt--tag-delete"],
"form" => "form-tag-delete",
"form-tag-delete" => $dbv,
];
return $vb;
}
function e2m_untagged($parameters = [])
{
global $settings, $_strings, $_config;
$gn = ys();
$untaggedView = new AePageableNotesView("e2m_untagged", $parameters);
$untaggedView->setPortionSize($settings["appearance"]["notes_per_page"]);
$untaggedView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$untaggedView->setWantPaging(true);
$untaggedView->setWantNewCommentsCount($gn);
$untaggedView->setWantReadHrefs($_config["count_reads"]);
$untaggedView->setWantControls($gn and !@$_config["read_only"]);
$untaggedView->setWantHiddenTags($gn);
$x0 =
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"LEFT OUTER JOIN `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk " .
"ON nk.`NoteID` = n.`ID` " .
"WHERE n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND n.`IsPublished`=1 " .
"AND nk.`SubsetID` IS NULL " .
df($gn);
$untaggedView->setSQLCountRequest("SELECT COUNT(*) Total " . $x0);
$untaggedView->setLimitlessSQLRequest(
"SELECT n.* " . $x0 . " ORDER BY n.`Stamp` DESC"
);
$ss = $_strings["pt--posts-without-tags"];
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => $_strings["pt--posts-without-tags"],
"notes" => $untaggedView->getNotesCTree(),
"pages" => $untaggedView->getPagesCTree(),
];
if ($untaggedView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-posts-without-tags"];
} elseif (!$untaggedView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function e2s_tag_edit()
{
global $_strings, $_config;
od();
$fs = $ng = $bq = $lw = "";
if (array_key_exists("tag-id", $_POST)) {
$fs = $_POST["tag-id"];
}
if (array_key_exists("tag", $_POST)) {
$ng = $_POST["tag"];
}
if (array_key_exists("page-title", $_POST)) {
$il = trim($_POST["page-title"], "\r\n");
}
if (array_key_exists("description", $_POST)) {
$bq = trim($_POST["description"], "\r\n");
}
if (array_key_exists("summary", $_POST)) {
$bw = trim($_POST["summary"], "\r\n");
}
if (array_key_exists("urlname", $_POST)) {
$lw = trim($_POST["urlname"], "\r\n");
}
list($gv, $sbv) = xa($ng);
$abv = 0;
$qbv = 1;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = " .
((int) $fs) .
"",
"get tag record to update"
);
$zbv = qm();
if (count($zbv) != 1) {
die();
}
$wb = $zbv[0];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `Keyword` = '" .
lm($gv) .
"' " .
"AND (`ID` != " .
((int) $fs) .
")",
"make sure new tag name does not conflict with existing ones"
);
$zbv = qm();
if (count($zbv) == 0) {
if ($qbv != $abv) {
cb();
}
e2_drop_caches_for_tag_($fs);
if ($gv === "") {
$gv = $wb["Keyword"];
hb($_strings["er--tag-must-have-name"], E2E_USER_ERROR);
}
$wb["ID"] = ((int) $fs);
$wb["Keyword"] = $gv;
$wb["PageTitle"] = $il;
$wb["Description"] = $bq;
$wb["Summary"] = $bw;
$wb["IsVisible"] = $sbv;
$v3 = qy("neasden", $wb["Description"]);
if (count($v3) > 0) {
g2($v3);
w2($v3);
}
$databaseConfiguration = bl();
fm($databaseConfiguration, "Keywords", $wb);
$jy = d(USER_DIR, $databaseConfiguration, "set", "t", $wb["ID"], $lw);
z1(eq("e2m_tag", ["tag-alias" => $jy]));
} else {
hb($_strings["er--cannot-rename-tag"], E2E_USER_ERROR);
k1();
}
die();
}
function e2s_tag_delete()
{
global $_config;
od();
$fs = ((int) $_POST["tag-id"]);
cb();
e2_drop_caches_for_tag_($fs);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$fs,
"delete note by ID"
);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Aliases` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `EntityType` = 't' " .
"AND `EntityID` = " .
((int) $fs),
"delete aliases after deleting note"
);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"NotesKeywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `KeywordID`=" .
$fs,
"delete tag bindings after deleting tag"
);
z1(eq("e2m_tags"));
}
function va()
{
global $settings, $_config;
$kbv = null;
if (CACHE_FAVTAGS and is_file(USER_DIR . CACHE_FILENAME_FAVTAGS)) {
$kbv = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_FAVTAGS)
);
}
$gn = ys();
if (!is_array($kbv)) {
try {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsFavourite`=1 ORDER BY `Keyword`",
"get favorite tags for tags menu"
);
$xbv = qm();
$kbv = [];
foreach ($xbv as $wb) {
if (!$wb["IsVisible"]) {
continue;
}
$ma["sort-id"] = "t" . $wb["ID"];
$ma["tag"] = htmlspecialchars(
$wb["Keyword"],
ENT_NOQUOTES,
"UTF-8"
);
$ma["title"] = gd($ma["tag"]);
$ma["href"] = eq("e2m_tag", ["*tag" => $wb]);
$ma["visible?"] = (bool) $wb["IsVisible"];
$ma["current?"] = false;
$ma["parent?"] = false;
$kbv[] = $ma;
}
if (CACHE_FAVTAGS) {
e3(USER_DIR . CACHE_FILENAME_FAVTAGS, serialize($kbv));
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Count not get tags menu from database");
}
}
}
if (!is_array($kbv)) {
return null;
}
foreach ($kbv as $k3 => $x3) {
if (!$gn and !$kbv[$k3]["visible?"]) {
unset($kbv[$k3]);
continue;
}
$kbv[$k3]["parent?"] = AeMainMenuManager::isParentTag($kbv[$k3]["tag"]);
$kbv[$k3]["current?"] = AeMainMenuManager::isCurrentTag(
$kbv[$k3]["tag"]
);
}
if (is_array(@$settings["menu_order"])) {
$pf = array_flip($settings["menu_order"]);
usort($kbv, function ($p5, $cj) use ($pf) {
$vj = @$pf[$p5["sort-id"]];
$bj = @$pf[$cj["sort-id"]];
if ($vj === false) {
$vj = count($pf);
}
if ($bj === false) {
$bj = count($pf);
}
return $vj - $bj;
});
}
return $kbv;
}
function ba($note_id)
{
global $_config;
$jb = [];
sm(
"SELECT k.* " .
"FROM `" .
$_config["db_table_prefix"] .
"Keywords` k, " .
"`" .
$_config["db_table_prefix"] .
"NotesKeywords` nk " .
"WHERE k.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk.`NoteID`=" .
((int) $note_id) .
" " .
"AND k.`ID`=nk.`KeywordID` " .
"ORDER BY `Keyword`",
"get tag records for note by id"
);
$jb = qm();
return $jb;
}
function ya($databaseConfiguration, $note_id, $n6)
{
na($databaseConfiguration, ["NoteID" => $note_id]);
foreach ($n6 as $ng) {
list($gv, $sbv) = xa($ng);
if ($gv === "") {
continue;
}
$ij = aa($databaseConfiguration, $gv);
if (!$ij) {
@unlink(USER_DIR . CACHE_FILENAME_TAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_FULL);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR_FULL);
b(true);
$ij["ID"] = fa($databaseConfiguration, $gv, $sbv);
}
am(
$databaseConfiguration,
"INSERT INTO `" .
$databaseConfiguration->getPrefix() .
"NotesKeywords` " .
"(`SubsetID`, `NoteID`, `KeywordID`) " .
"VALUES (" .
((int) $databaseConfiguration->getSubset()) .
", " .
((int) $note_id) .
", " .
((int) $ij["ID"]) .
")",
"add new tag bindings"
);
}
}
function na($databaseConfiguration, $ebv)
{
$rbv = [];
foreach (["ID", "NoteID", "KeywordID"] as $x) {
if (array_key_exists($x, $ebv)) {
$ah[] = "`" . $x . "`" . "='" . lm($ebv[$x]) . "'";
if ($x == "ID") {
$tbv = "tagbinging-id";
}
if ($x == "NoteID") {
$tbv = "tagbinging-note-id";
}
if ($x == "KeywordID") {
$tbv = "tagbinging-tag-id";
}
$rbv[$tbv] = $ebv[$x];
}
}
$e2_ =
"DELETE FROM `" .
$databaseConfiguration->getPrefix() .
"NotesKeywords` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND " .
implode(" AND ", $ah);
am($databaseConfiguration, $e2_);
}
function ma($fs, $jbv)
{
global $_config;
sm(
"SELECT `ID`, `Keyword`, `OriginalAlias` " .
"FROM `" .
$_config["db_table_prefix"] .
"Keywords` k " .
"WHERE k.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsVisible` = 1 " .
"AND k.`ID` IN (" .
"SELECT `KeywordID` FROM (" .
"SELECT COUNT(`NoteID`) NotesCount, `KeywordID` " .
"FROM `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk " .
"WHERE nk.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk.`NoteID` IN (" .
"SELECT nk2.`NoteID` " .
"FROM `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk2 " .
"WHERE nk2.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk2.`KeywordID`=" .
$fs .
") " .
"GROUP BY nk.`KeywordID` " .
"HAVING NotesCount > 1 " .
"ORDER BY NotesCount DESC " .
"LIMIT 1, " .
$jbv .
") k_ids" .
")",
"find related tags"
);
$u9 = [];
foreach (qm() as $wb) {
if ($wb["ID"] === $fs) {
continue;
}
$u9[] = [
"name" => htmlspecialchars($wb["Keyword"], ENT_NOQUOTES, "UTF-8"),
"href" => eq("e2m_tag", ["*tag" => $wb]),
"visible?" => true,
];
}
return $u9;
}
function fa(AeDatabaseConfiguration $databaseConfiguration, $gv, $sbv)
{
$wb = [
"Keyword" => $gv,
"OriginalAlias" => d(
USER_DIR,
$databaseConfiguration,
"find",
"",
"",
$gv
),
"Description" => "",
"IsVisible" => $sbv,
];
$wb = mm($databaseConfiguration, "Keywords", $wb);
$hbv = d(USER_DIR, $databaseConfiguration, "set", "t", $wb["ID"], $gv);
if ($hbv != $wb["OriginalAlias"]) {
$wb["OriginalAlias"] = $hbv;
fm($databaseConfiguration, "Keywords", $wb);
}
return $wb["ID"];
}
function da($parameters)
{
if (($gbv = sa()) === null) {
return [];
}
$z3["each"] = $gbv;
if (count($z3["each"]) > 0) {
$z3["href"] = eq("e2m_tags");
}
if (($wbv = va()) !== null) {
$z3["menu-each"] = $wbv;
}
return $z3;
}
function sa($ubv = false)
{
global $_config;
$gn = ys();
$of = USER_DIR . CACHE_FILENAME_TAGS;
if ($gn) {
$of = USER_DIR . CACHE_FILENAME_TAGS_AUTHOR;
}
if ($ubv) {
$of = USER_DIR . CACHE_FILENAME_TAGS_FULL;
if ($gn) {
$of = USER_DIR . CACHE_FILENAME_TAGS_AUTHOR_FULL;
}
}
$ibv = null;
if (CACHE_TAGS and is_file($of)) {
$ibv = @unserialize(file_get_contents($of));
}
if (!is_array($ibv)) {
try {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"ORDER BY `Keyword`",
"get all tags"
);
$obv = [];
foreach (qm() as $wb) {
$gv["id"] = (int) $wb["ID"];
$gv["tag"] = htmlspecialchars(
$wb["Keyword"],
ENT_NOQUOTES,
"UTF-8"
);
$gv["tag-dotted"] = ka($wb);
$gv["pinned?"] = false;
$gv["visible?"] = (bool) $wb["IsVisible"];
$gv["notes-count"] = 0;
$gv["last-used"] = 0;
$gv["freshness"] = 0;
$gv["weight"] = 0;
if ($ubv) {
$gv["href"] = eq("e2m_tag", ["*tag" => $wb]);
}
$obv[$wb["ID"]] = $gv;
}
sm(
"SELECT nk.KeywordID, COUNT(DISTINCT n.ID) as Count, max(n.Stamp) as LastUsed " .
"FROM `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk, " .
"`" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE nk.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND n.`IsPublished` = 1 " .
df($gn) .
"AND nk.`NoteID` = n.`ID` " .
"GROUP BY nk.KeywordID",
"get tags ordering info"
);
$pbv = 0;
$c3v = 0;
$v3v = 0;
foreach (qm() as $b3v) {
if (!isset($obv[$b3v["KeywordID"]])) {
unset($obv[$b3v["KeywordID"]]);
continue;
}
$ma = &$obv[$b3v["KeywordID"]];
$ma["notes-count"] = $b3v["Count"];
if (@$ma["last-used"] < $b3v["LastUsed"]) {
$ma["last-used"] = $b3v["LastUsed"];
$y3v = (time() - $ma["last-used"]) / SECONDS_IN_A_YEAR;
$ma["freshness"] = pow(1 / 2, $y3v);
}
$pbv = max($pbv, $ma["notes-count"]);
$c3v = max($c3v, $ma["freshness"]);
$v3v = max($v3v, $ma["notes-count"] * $ma["freshness"]);
}
$ibv = [];
foreach ($obv as $gb => $x3) {
if (!$gn and $x3["notes-count"] == 0) {
continue;
}
if (!$gn and !$x3["visible?"]) {
continue;
}
$n3v = mb_strtolower($x3["tag"]);
$ibv[$n3v] = $x3;
if ($c3v != 0) {
$ibv[$n3v]["freshness"] = $x3["freshness"] / $c3v;
} else {
$ibv[$n3v]["freshness"] = 0;
}
if ($v3v != 0) {
$ibv[$n3v]["weight"] =
($x3["freshness"] * $x3["notes-count"]) / $v3v;
} else {
$ibv[$n3v]["weight"] = 0;
}
if ($ibv[$n3v]["pinned?"]) {
$ibv[$n3v]["weight"] = 1;
}
}
if (CACHE_TAGS) {
e3($of, serialize($ibv));
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Could not get tags from database");
}
}
}
return $ibv;
}
function aa(AeDatabaseConfiguration $databaseConfiguration, $fbv)
{
am(
$databaseConfiguration,
"SELECT * FROM `" .
$databaseConfiguration->getPrefix() .
"Keywords` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `Keyword`='" .
lm($fbv) .
"'",
"get tag by name"
);
$k3 = qm();
if (isset($k3[0])) {
return $k3[0];
} else {
return null;
}
}
function qa(AeDatabaseConfiguration $databaseConfiguration, $m3v)
{
am(
$databaseConfiguration,
"SELECT * FROM `" .
$databaseConfiguration->getPrefix() .
"Keywords` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `OriginalAlias`='" .
lm($m3v) .
"'",
"get tag by legacy urlname name"
);
$kb = qm();
if (isset($kb[0])) {
return $kb[0];
} else {
return null;
}
}
function la($ey)
{
global $_config;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`='" .
((int) $ey) .
"'",
"get tag by id"
);
$kb = qm();
if (isset($kb[0])) {
return $kb[0];
} else {
return null;
}
}
function e2_tagrecs_with_parameters_($parameters)
{
$f3v = [];
if (@$parameters["tag-alias"] or $parameters["tag-alias"] === "0") {
$f3v = explode(",", $parameters["tag-alias"]);
}
$jb = [];
foreach ($f3v as $m3v) {
if ($m3v or $m3v === "0") {
if (
($og = (f(@$m3v) and $og["type"] == "t")) and
($wb = la($og["id"]))
) {
$jb[] = $wb;
} else {
if ($d3v = qa(bl(), $m3v)) {
$jb[] = $d3v;
}
}
}
}
return $jb;
}
function ka($wb)
{
$s3v = htmlspecialchars($wb["Keyword"], ENT_COMPAT, "UTF-8");
if (!$wb["IsVisible"]) {
$s3v = "." . $s3v;
}
return $s3v;
}
function xa($s3v)
{
if (@$s3v[0] === ".") {
return [trim(substr($s3v, 1), ". \t\n\r\0"), false];
} else {
return [$s3v, true];
}
}
function ea($mf)
{
$gh = n1("H", $mf);
if ($gh <= 4) {
return 4;
} elseif ($gh <= 10) {
return 1;
} elseif ($gh <= 16) {
return 2;
} elseif ($gh <= 22) {
return 3;
} else {
return 4;
}
}
function ra($a3v, $q3v = null)
{
global $_strings;
if ($q3v === null) {
$q3v = pa();
}
$xd = time();
$l3v = y1("d.m.Y", $xd, $q3v);
$z3v = y1("d.m.Y", $a3v, $q3v);
$k3v = SECONDS_IN_A_MINUTE;
$x3v = SECONDS_IN_AN_HOUR;
$e3v = ea($xd);
$r3v = ea($a3v);
$t3v = $xd - $a3v;
if ($t3v < 0) {
return $_strings["tt--from-the-future"];
}
if ($t3v >= 0 and $t3v < 54) {
return $_strings["tt--just-now"];
}
if ($t3v >= 54 and $t3v < 108) {
return $_strings["tt--one-minute-ago"];
}
$j3v = $t3v + 12;
$h3v = floor($j3v / $k3v);
if ($t3v >= 108 and $t3v < 54 * $k3v) {
return e2l_get_string("tt--minutes-ago", ["minutes" => $h3v]);
}
if ($t3v >= 54 * $k3v and $t3v < 108 * $k3v) {
return $_strings["tt--one-hour-ago"];
}
$j3v = $t3v + 12 * $k3v;
$g3v = floor($j3v / $x3v);
if ($t3v >= 108 * $k3v and $t3v < 4 * $x3v) {
return e2l_get_string("tt--hours-ago", ["hours" => $g3v]);
}
$l = y1("G:i", $a3v, $q3v);
if ($t3v >= 4 * $x3v and $e3v > $r3v and $l3v == $z3v) {
return $_strings["tt--today"];
}
if ($xd - $a3v <= 7884000) {
return e2l_get_string("tt--date", [
"day" => y1("j", $a3v, $q3v),
"month" => y1("m", $a3v, $q3v),
]);
}
return y1("Y", $a3v, $q3v);
}
function ta($a3v, $q3v = null)
{
global $_strings;
$t3v = time() - $a3v;
if ($t3v < 0) {
return $_strings["tt--from-the-future"];
}
if ($t3v == 0) {
return $_strings["tt--now"];
}
$w3v = [
[1, "tt--seconds-short"],
[SECONDS_IN_A_MINUTE, "tt--minutes-short"],
[SECONDS_IN_AN_HOUR, "tt--hours-short"],
[SECONDS_IN_A_DAY, "tt--days-short"],
[SECONDS_IN_A_MONTH, "tt--months-short"],
[SECONDS_IN_A_YEAR, "tt--years-short"],
[SECONDS_IN_A_YEAR + SECONDS_IN_A_MONTH, ""],
];
for ($gb = 0; $gb < count($w3v); ++$gb) {
if ($t3v >= $w3v[$gb][0] and $t3v < $w3v[$gb + 1][0]) {
return e2l_get_string($w3v[$gb][1], [
"value" => floor($t3v / $w3v[$gb][0]),
]);
}
}
if ($q3v === null) {
$q3v = pa();
}
return y1("Y", $a3v, $q3v);
}
function e2m_timezone()
{
global $_strings, $settings;
$u3v = [
"form-action" => eq("e2s_select_timezone"),
"submit-text" => $_strings["fb--select"],
"timezone-selector" => wa($settings["timezone"]["offset"], 1),
"dst?" => $settings["timezone"]["is_dst"],
];
return [
"title" => $_strings["pt--default-timezone"],
"heading" => $_strings["pt--default-timezone"],
"form" => "form-timezone",
"form-timezone" => $u3v,
];
}
function ja()
{
global $_strings;
$i3v = [
-720 => "",
-660 => "",
-600 => "",
-540 => "",
-480 => $_strings["tt--zone-pt"],
-420 => $_strings["tt--zone-mt"],
-360 => $_strings["tt--zone-ct"],
-300 => $_strings["tt--zone-et"],
-240 => "",
-210 => "",
-180 => "",
-120 => "",
-60 => "",
0 => $_strings["tt--zone-gmt"],
60 => $_strings["tt--zone-cet"],
120 => $_strings["tt--zone-eet"],
180 => "",
210 => "",
240 => $_strings["tt--zone-msk"],
270 => "",
300 => "",
330 => "",
345 => "",
360 => $_strings["tt--zone-ekt"],
390 => "",
420 => "",
480 => "",
540 => "",
570 => "",
600 => "",
660 => "",
720 => "",
780 => "",
840 => "",
];
return $i3v;
}
function ha($t3)
{
$i3v = ja();
return @$i3v[(int) $t3 / SECONDS_IN_A_MINUTE];
}
function ga($t3)
{
$o3v = "+";
if ($t3 < 0) {
$o3v = "–";
}
$p3v = str_pad((int) (abs($t3) / 3600), 2, "0", STR_PAD_LEFT);
$cyv = str_pad((abs($t3) / 60) % 60, 2, "0", STR_PAD_LEFT);
return "GMT" . $o3v . $p3v . ":" . $cyv;
}
function wa($vyv, $byv = "")
{
global $_strings;
$i3v = ja();
$vb = "";
if (!$byv) {
$byv = count($i3v);
}
$vb .= '<select class="e2-select" name="offset" size="' . $byv . '">';
foreach ($i3v as $t3 => $yyv) {
$nyv = "";
if ($t3 * SECONDS_IN_A_MINUTE == $vyv) {
$nyv = ' selected="selected"';
}
$vb .= "<option" . $nyv . ' value="' . $t3 . '">';
$o3v = "";
if ($t3 < 0) {
$o3v = "";
}
if ($t3 > 0) {
$o3v = "+";
}
$p3v = (int) (abs($t3 * SECONDS_IN_A_MINUTE) / 3600);
$cyv = (int) ((abs($t3 * SECONDS_IN_A_MINUTE) / 60) % 60);
if ($p3v) {
$vb .=
$o3v .
" " .
$p3v .
" " .
$_strings["gs--timezone-offset-hours"] .
" " .
($cyv
? $cyv . " " . $_strings["gs--timezone-offset-minutes"]
: "");
if ($yyv) {
$vb .= " (" . $yyv . ")";
}
} else {
$vb .= $yyv;
}
$vb .= "</option>";
}
$vb .= "</select>";
return $vb;
}
function ua($ob)
{
global $settings;
if ($settings["timezone"] === $ob) {
return true;
}
$settings["timezone"] = $ob;
return @e3(
USER_DIR . "settings.json",
json_encode($settings, E2_JSON_STYLE)
);
}
function e2s_select_timezone()
{
global $_strings;
od();
if (@$_POST["offset"] >= -720 and @$_POST["offset"] <= 780) {
$ob["offset"] = @$_POST["offset"] * SECONDS_IN_A_MINUTE;
$ob["is_dst"] = isset($_POST["is_dst"]);
}
if (ua($ob)) {
z1(eq("e2m_settings"));
} else {
hb($_strings["er--settings-not-saved"], E2E_PERMISSIONS_ERROR);
z1(eq("e2m_timezone"));
}
}
function ia($r)
{
return ["offset" => (int) $r["Offset"], "is_dst" => (bool) $r["IsDST"]];
}
function oa()
{
return ["offset" => 0, "is_dst" => false];
}
function pa()
{
global $settings;
if (array_key_exists("timezone", $settings)) {
return $settings["timezone"];
} else {
return oa();
}
}
function c1($ob, $myv)
{
if (@$ob["is_dst"]) {
$fyv = (int) date("I", $myv);
$dyv = date("Z", $myv) - $fyv * SECONDS_IN_AN_HOUR;
$syv = $ob["offset"];
$ayv = $syv - $dyv;
$qyv = date("I", $myv + $ayv);
return $qyv;
} else {
return 0;
}
}
function v1($ob, $myv)
{
if ($ob and is_array($ob)) {
return $ob["offset"] + c1($ob, $myv) * SECONDS_IN_AN_HOUR;
}
}
function b1($myv)
{
return v1(pa(), $myv);
}
function y1($lyv, $w4, $ob)
{
return gmdate($lyv, $w4 + v1($ob, $w4));
}
function n1($lyv, $w4)
{
return y1($lyv, $w4, pa());
}
function m1($gm, $wm = false, $um = false)
{
if (is_numeric($um)) {
$zyv = gmmktime(0, 0, 0, (int) $wm, (int) $um, (int) $gm);
$kyv = gmmktime(0, 0, 0, (int) $wm, $um + 1, (int) $gm) - 1;
} elseif (is_numeric($wm)) {
$zyv = gmmktime(0, 0, 0, (int) $wm, 1, (int) $gm);
$kyv = gmmktime(0, 0, 0, $wm + 1, 1, (int) $gm) - 1;
} else {
$zyv = gmmktime(0, 0, 0, 1, 1, (int) $gm);
$kyv = gmmktime(0, 0, 0, 1, 1, $gm + 1) - 1;
}
return [$zyv, $kyv];
}
function f1($ob, $gm, $wm = false, $um = false)
{
list($zyv, $kyv) = m1($gm, $wm, $um);
$zyv -= v1($ob, $zyv);
$kyv -= v1($ob, $kyv);
return [$zyv, $kyv];
}
function d1($gm, $wm = false, $um = false)
{
return f1(pa(), $gm, $wm, $um);
}
function s1($gm, $wm = false, $um = false)
{
$xyv = 13;
$eyv = -12;
$xyv += 1;
$eyv -= 1;
list($zyv, $kyv) = m1($gm, $wm, $um);
$zyv -= $xyv * 3600;
$kyv -= $eyv * 3600;
return [$zyv, $kyv];
}
function a1($t3)
{
if ((int) @$t3 > 0) {
return (string) "+" . abs(@$t3);
} elseif ((int) @$t3 < 0) {
return (string) "-" . abs(@$t3);
} else {
return "";
}
}
function q1($myv, $ryv = "")
{
$tyv = b1($myv);
$o3v = $tyv >= 0 ? "+" : "-";
$tyv = abs($tyv);
$wh = $tyv % 60;
$tyv -= $wh;
$wm = ($tyv % 3600) / 60;
$tyv -= $wm * 60;
$gh = $tyv / 3600;
if ($gh < 10) {
$gh = "0" . $gh;
}
if ($wm < 10) {
$wm = "0" . $wm;
}
return $o3v . $gh . $ryv . $wm;
}
function l1($jyv)
{
global $settings;
if (is_numeric($jyv)) {
$h3["offset"] = SECONDS_IN_A_MINUTE * $jyv;
$h3["is_dst"] = false;
$hyv = SECONDS_IN_A_MINUTE * $jyv - SECONDS_IN_AN_HOUR;
$gyv = ["offset" => $hyv, "is_dst" => true];
$gyv = (int) v1($gyv, time());
if ($h3["offset"] == $gyv) {
$h3["offset"] = $hyv;
$h3["is_dst"] = true;
}
} else {
if (array_key_exists("timezone", $settings)) {
$h3 = $settings["timezone"];
} else {
$h3["offset"] = 0;
$h3["is_dst"] = false;
}
}
return $h3;
}
function z1($m1 = "")
{
global $errors;
@session_start();
$_SESSION["errors"] = $errors;
if (substr($m1, 0, strlen(AeEnv::$i) + 3) != AeEnv::$i . "://") {
header("Location: " . AeEnv::$p . $m1);
} else {
header("Location: " . $m1);
}
flush();
die();
}
function k1()
{
$wyv = (string) @$_SERVER["HTTP_REFERER"];
z1($wyv);
}
function x1($wt = "")
{
$uyv = str_replace("/", "--", trim(AeEnv::$w . "/" . AeEnv::$u, "/"));
if ($uyv !== "") {
$uyv .= "-";
}
$url = AeEnv::$o;
$ck = substr_count($_SERVER["HTTP_HOST"], ".");
$vb = $uyv . @str_repeat("_", $ck) . $wt;
return $vb;
}
function e1($wt, $vv = "", $iyv = true)
{
$oyv = $iyv ? time() + 3600 * 24 * 365 : 0;
$v5 = $_SERVER["HTTP_HOST"];
$pyv = substr_count($v5, ".");
if ($pyv < 3) {
$v5 = str_repeat(".", 3 - $pyv) . $v5;
}
setcookie(x1($wt), $vv, $oyv, "/");
}
function r1($cnv, $m4, $vnv = "")
{
if (trim($m4) != "") {
$m4 = explode($cnv, $m4);
foreach ($m4 as $gb => $k3) {
$m4[$gb] = trim($k3);
}
foreach ($m4 as $gb => $k3) {
if ($k3 == "") {
unset($m4[$gb]);
}
}
$bnv = array_unique($m4);
if ("sort" == $vnv) {
sort($bnv);
}
return $bnv;
} else {
return [];
}
}
function t1($m4)
{
$tq = [];
if (is_file(SYSTEM_DEFAULTS_DIR . "romanize.txt")) {
$tq = file(SYSTEM_DEFAULTS_DIR . "romanize.txt");
}
$ynv = $g5 = "";
foreach ($tq as $gb => $bf) {
if (!($gb % 2)) {
$ynv .= rtrim($bf) . " ";
} else {
$g5 .= rtrim($bf) . " ";
}
if ($gb % 2) {
while (mb_strlen($g5) < mb_strlen($ynv)) {
$g5 .= " ";
}
while (mb_strlen($g5) > mb_strlen($ynv)) {
$ynv .= " ";
}
}
}
$nnv = "";
$mnv = -1;
for ($gb = 0; $gb < mb_strlen($ynv); ++$gb) {
$nvv = mb_substr($ynv, $gb, 1);
if ($nvv != " ") {
$nnv .= $nvv;
if ($mnv == -1) {
$mnv = $gb;
}
} elseif ($nnv) {
$fnv = trim(
mb_substr($g5, $mnv, mb_strpos($g5, " ", $mnv + 1) - $mnv)
);
$xb = [$nnv, $fnv];
$dnv[mb_strlen($nnv)][] = $xb;
$nnv = "";
$mnv = -1;
}
}
$snv = [];
for ($gb = count($dnv); $gb > 0; --$gb) {
foreach ($dnv[$gb] as $xb) {
$snv[$xb[0]] = $xb[1];
}
}
return strtr($m4, $snv);
}
function j1($p5, $cj, $anv = 0)
{
if ($cj == 0) {
return 0;
}
$qnv = round(($p5 / $cj) * 100, $anv);
$lnv = pow(10, -$anv);
if ($p5 > 0 and $qnv == 0) {
$qnv = $lnv;
}
if ($p5 < $cj and $qnv == 100) {
$qnv = 100 - $lnv;
}
return $qnv;
}
function h1($znv, $action, $w4)
{
if (!is_array($znv)) {
$znv = [];
}
if ($action == "add") {
$znv = array_unique(array_merge($znv, $w4));
}
if ($action == "remove") {
unset($znv[array_search($w4, $znv)]);
}
if (!is_array($znv)) {
$znv = [];
}
return $znv;
}
function g1($zb)
{
$parameters = $zb["parameters"];
$dl = ["success" => false];
$zb["flipping-function"]($parameters);
$knv = $parameters;
$knv["value"] = !$parameters["value"];
$dl = [
"success" => true,
"data" => [
"flag-now-on" => $parameters["value"] == 1,
"new-href" => eq($zb["candy-name"], $knv),
],
];
if (
array_key_exists("result", $_POST) and
$_POST["result"] == "ajaxresult"
) {
$dl = json_encode($dl);
die($dl);
} else {
z1(eq($zb["redirect-candy"], $parameters));
}
}
function w1($m4)
{
($yp = @$_SERVER["HTTP_USER_AGENT"]) or ($yp = "");
$xnv = strstr($yp, "iPhone") || strstr($yp, "iPad");
$env = strstr($yp, "Macintosh");
if ($xnv) {
return "";
}
if ($m4 == "submit") {
if ($env) {
return "⌃ ↩";
} else {
return "Ctrl + Enter";
}
}
if ($m4 == "livesave") {
if ($env) {
return "⌘ S";
} else {
return "Ctrl + S";
}
}
if ($m4 == "navigation") {
if ($env) {
return "⌥";
} else {
return "Ctrl";
}
}
if ($m4 == "navigation-later") {
if ($env) {
return "⌥ ↑";
} else {
return "Ctrl + ↑";
}
}
if ($m4 == "navigation-earlier") {
if ($env) {
return "⌥ ↓";
} else {
return "Ctrl + ↓";
}
}
}
function u1($e1)
{
$e1 = str_replace("<", "<", $e1);
$e1 = str_replace(">", ">", $e1);
return $e1;
}
function i1($e1)
{
$e1 = str_replace('"', """, $e1);
return $e1;
}
function o1($vv, $rnv)
{
return str_replace(".", ",", round($vv, $rnv));
}
function e2_stripslashes_array($ys)
{
return is_array($ys)
? array_map("e2_stripslashes_array", $ys)
: stripslashes($ys);
}
function p1()
{
if (version_compare(PHP_VERSION, "7.4") >= 0) {
return;
}
if (get_magic_quotes_runtime()) {
set_magic_quotes_runtime(0);
}
if (get_magic_quotes_gpc()) {
$_GET = e2_stripslashes_array($_GET);
$_POST = e2_stripslashes_array($_POST);
$_COOKIE = e2_stripslashes_array($_COOKIE);
$_REQUEST = e2_stripslashes_array($_REQUEST);
}
}
function cq($uo)
{
return sprintf("%u", ip2long($uo));
}
function vq($ka)
{
return long2ip(sprintf("%d", $ka));
}
function e2_decline_for_number($e1, $ka = null)
{
$tnv = $e1;
if ($ka === null) {
$ka = substr($e1, 0, strpos($e1, " "));
$tnv = substr($e1, strpos($e1, " ") + 1);
}
$jnv = strpos($tnv, "(");
$hnv = strpos($tnv, ")");
if ($hnv > $jnv) {
$gnv = substr($tnv, $jnv, $hnv - $jnv + 1);
}
$wnv = explode(",", trim(@$gnv, "()"));
if (count($wnv) == 2) {
array_unshift($wnv, "");
}
$unv = [2, 0, 1, 1, 1, 2, 2, 2, 2, 2];
if ($ka % 100 > 10 and $ka % 100 < 20) {
$inv = 2;
} else {
$inv = $unv[$ka % 10];
}
$i7 = $wnv[$inv];
$e1 = str_replace($gnv, $i7, $e1);
if (strstr($e1, "(") and strstr($e1, ")")) {
return e2_decline_for_number($e1, $ka);
} else {
return $e1;
}
}
function bq($onv)
{
$up = glob($onv, GLOB_NOSORT);
if (is_array($up)) {
foreach ($up as $od) {
@unlink($od);
}
}
}
function yq($ce)
{
$up = glob($ce . "*", GLOB_NOSORT);
if (is_array($up)) {
foreach ($up as $od) {
if (basename($od) != "." and basename($od) != "..") {
if (is_dir($od)) {
if (yq($od . "/")) {
if (!@rmdir($od)) {
return false;
}
} else {
return false;
}
} else {
@unlink($od);
}
}
}
return true;
} else {
return false;
}
}
function nq($pnv)
{
$pnv = trim($pnv, "/");
$pnv = explode("/", $pnv);
$ce = "";
foreach ($pnv as $ih) {
$ce = $ce . $ih;
if (!is_dir($ce)) {
if (@mkdir($ce)) {
@chmod($ce, E2_NEW_FILES_RIGHTS);
} else {
return false;
}
}
$ce = $ce . "/";
}
return true;
}
function mq($pnv)
{
return preg_replace("/\/([^\/]+?)\/\.\./", "", $pnv);
}
function fq($m4)
{
$cmv = get_html_translation_table(HTML_ENTITIES);
$cmv = array_flip($cmv);
return strtr($m4, $cmv);
}
function dq($vmv = null)
{
if (null == $vmv) {
$vmv = microtime();
}
list($bmv, $t3v) = explode(" ", $vmv);
return (float) $bmv + (float) $t3v;
}
function _A($e1)
{
global $_candy, $_current_url;
if (
preg_match('/\<a href\=\"(.*?)\"[^>]*\>(.*?)\<\/a\>/si', $e1, $v6) and
($v6[1] === "" or
$v6[1] === $_current_url or
AeEnv::$i . "://" . AeEnv::$server . $v6[1] === $_current_url or
AeEnv::$p . $v6[1] === $_current_url or
$_candy == "e2m_install")
) {
return $v6[2];
} else {
return $e1;
}
}
function _AT($s1)
{
global $_current_url;
return $s1 === "" or
$s1 === $_current_url or
AeEnv::$i . "://" . AeEnv::$server . $s1 === $_current_url or
AeEnv::$p . AeEnv::$u . $s1 === $_current_url;
}
function _READS($u3)
{
if (!empty($u3["read-count"])) {
return $u3["read-count"];
}
return AeNoteReadCountsProvider::getReadCountForNoteID($u3["id"]);
}
function _IMGSRC($od)
{
return pf($od);
}
function _SVG($od)
{
return c2($od);
}
function _COLOR($b, $y, $ymv, $nmv = 1)
{
if (strlen($b) != 3 and strlen($b) != 6) {
return "f0f";
}
if (strlen($y) != 3 and strlen($y) != 6) {
return "f0f";
}
if (strlen($b) == 3) {
$b = $b[0] . $b[0] . $b[1] . $b[1] . $b[2] . $b[2];
}
if (strlen($y) == 3) {
$y = $y[0] . $y[0] . $y[1] . $y[1] . $y[2] . $y[2];
}
$fh = [
$b[0] . $b[1],
$b[2] . $b[3],
$b[4] . $b[5],
$y[0] . $y[1],
$y[2] . $y[3],
$y[4] . $y[5],
];
foreach ($fh as $k3 => $x3) {
$fh[$k3] = hexdec($x3);
}
$d5 = [
$fh[0] + pow($ymv, $nmv) * ($fh[3] - $fh[0]),
$fh[1] + pow($ymv, $nmv) * ($fh[4] - $fh[1]),
$fh[2] + pow($ymv, $nmv) * ($fh[5] - $fh[2]),
];
$mmv = "";
foreach ($d5 as $k3 => $x3) {
$mmv .= str_pad(dechex($x3), 2, "0", STR_PAD_LEFT);
}
return $mmv;
}
function _DT($lyv, $fmv)
{
if (!$fmv) {
return "";
}
list($mf, $ob) = $fmv;
$vb = $lyv;
$jn = y1("m", $mf, $ob);
$vb = str_replace("{zone}", e2__escape_all(ga($ob["offset"])), $vb);
$vb = str_replace(
"{month}",
e2__escape_all(e2l_get_string("um--month", ["month" => $jn])),
$vb
);
$vb = str_replace(
"{month-short}",
e2__escape_all(e2l_get_string("um--month-short", ["month" => $jn])),
$vb
);
$vb = str_replace(
"{month-g}",
e2__escape_all(e2l_get_string("um--month-g", ["month" => $jn])),
$vb
);
$vb = y1($vb, $mf, $ob);
return $vb;
}
function _AGO($fmv)
{
return ta($fmv[0], [
"offset" => $fmv[1]["offset"],
"is_dst" => $fmv[1]["is_dst"],
]);
}
function _NUM($e1)
{
return e2_decline_for_number($e1);
}
function _CSS($dmv)
{
return wf($dmv);
}
function _CSS_HREF($dmv)
{
return v2($dmv);
}
function _JS($smv)
{
return uf($smv);
}
function _LIB($uu)
{
return if_($uu);
}
function _T($ru)
{
echo hf($ru);
}
function _T_DEFER($name)
{
echo rf($name);
}
function _X($ru)
{
echo jf($ru);
}
function _T_FOR($ru, $amv = null)
{
global $content;
if ($amv === null) {
$amv = $ru;
}
if (array_key_exists($amv, $content)) {
echo hf($ru);
} else {
echo "";
}
}
function _FIT($ak, $qk)
{
}
function _GUIDES($qmv = false)
{
global $_olba_guides;
if (is_array($qmv)) {
$_olba_guides = $qmv;
}
if (!is_array($_olba_guides)) {
return;
}
$lmv =
'<div style="position: fixed; width: 100%; height: 100%; z-index: -100">';
$zmv = 0;
$kmv = $_olba_guides;
$kmv[] = 100;
foreach ($kmv as $gb => $xmv) {
if ($xmv == 100) {
break;
}
$zmv += $xmv;
$lmv .=
'<div style="position: fixed; left: ' .
$xmv .
'%; width: 0; height: 100%; border-left: 1px #000 dotted; opacity: .2; -webkit-opacity: .2; -moz-opacity: .2"></div>';
$emv =
'position: absolute; padding: 2px 3px; top: 0; font-size: 9px; background: #ccc; color: #000; font-family: "Verdana", sans-serif; opacity: .8; -webkit-opacity: .8; -moz-opacity: .8';
if ($kmv[$gb + 1] - $kmv[$gb] < 4) {
$lmv .=
'<div style="' .
$emv .
"; right: " .
(100 - $xmv) .
'%; border-bottom-left-radius: .5em; -webkit-border-bottom-left-radius: .5em; -moz-border-bottom-left-radius: .5em;">' .
$xmv .
"%</div>";
} else {
$lmv .=
'<div style="' .
$emv .
"; left: " .
$xmv .
'%; border-bottom-right-radius: .5em; -webkit-border-bottom-right-radius: .5em; -moz-border-bottom-right-radius: .5em;">' .
$xmv .
"%</div>";
}
}
$lmv .= "</div>";
$_olba_current_col = 0;
return $lmv;
}
function _S($m4)
{
global $_strings;
return $_strings[$m4];
}
function _SHORTCUT($name)
{
return w1($name);
}
function e2__escape_all($m4)
{
$vb = "";
for ($gb = 0; $gb < mb_strlen($m4); ++$gb) {
$vb .= "\\" . mb_substr($m4, $gb, 1);
}
return $vb;
}
function sq($ynv)
{
global $_db, $_instance_config, $_strings;
$rmv = "v" . $ynv;
$tmv = "v" . E2_VERSION;
$jmv = lq($ynv);
$hmv = lq(E2_VERSION);
if ($jmv === $hmv) {
$jmv = $rmv;
$hmv = $tmv;
} else {
$jmv .= "(" . $rmv . ")";
$hmv .= "(" . $tmv . ")";
}
$gmv = lq(3239) . "(v3239)";
if (!$_instance_config["allow_update"]) {
return ["stub" => ps("update-disallowed")];
}
if (
E2_VERSION < $ynv and
!$_instance_config["dev_ignore_version_mismatch"]
) {
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--confused"],
"text" =>
"<p>" .
e2l_get_string("gs--downdate-explanation", [
"dr" => $jmv,
"rr" => $hmv,
]) .
"</p>",
]),
];
}
if ($ynv < 3239) {
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--multi-step-update"],
"text" =>
"<p>" .
e2l_get_string("gs--multi-step-update-p1", [
"dr" => $jmv,
"rr" => $hmv,
"ur" => $gmv,
]) .
"</p>" .
"<p>" .
e2l_get_string("gs--multi-step-update-p2", [
"dr" => $jmv,
"rr" => $hmv,
"ur" => $gmv,
]) .
"</p>",
]),
];
}
if (qq()) {
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--updating"],
"text" => "<p>" . $_strings["gs--this-takes-seconds"] . "</p>",
"button" => $_strings["fb--retry"],
]),
];
}
$wmv = @unserialize(file_get_contents(INSTANCE_DIR . "migration.psa"));
if (!is_array($wmv)) {
$wmv = [];
}
if ($_instance_config["log_updates"]) {
Log::$a = true;
if (Log::$a) {
qn('update-$');
}
}
if (Log::$a) {
__log("Update from v" . $ynv . " to v" . E2_VERSION . " {");
}
$umv = $ynv < 3601;
$databaseConfigurationsToMigrate = [];
try {
if (Log::$a) {
__log("Update instance");
}
if ($_instance_config["db"] !== null) {
$instanceDatabaseConfiguration = new AeDatabaseConfiguration(
"instance-config",
INSTANCE_DIR . BACKUP_DIRNAME,
$_instance_config["db"]["server"],
$_instance_config["db"]["user_name"],
$_instance_config["db"]["passw"],
$_instance_config["db"]["name"],
$_instance_config["db_table_prefix"]
);
if ($_instance_config["backup_before_update"]) {
rm($instanceDatabaseConfiguration);
}
cm($instanceDatabaseConfiguration);
if (Log::$a) {
__log(
'Instance has migrateable database table set "' .
$instanceDatabaseConfiguration->getTablesKeyString() .
'"'
);
}
if (@$wmv[$instanceDatabaseConfiguration->getTablesKeyString()]) {
if (Log::$a) {
__log("Marked as already migrated, will skip");
}
} else {
$imv = aq($instanceDatabaseConfiguration);
$instanceDatabaseConfiguration->setSubset($imv);
if (Log::$a) {
__log(
"Will set subset " . $imv . " for subset-zero records"
);
}
$databaseConfigurationsToMigrate[
$instanceDatabaseConfiguration->getTablesKeyString()
] = $instanceDatabaseConfiguration;
}
}
mn();
AeFileManager::forceInstanceDirectories();
$omv = vl();
if (Log::$a) {
__log("Update " . count($omv) . " users {");
}
$mq = [];
foreach ($omv as $ccv) {
$pmv = oq($ccv, $_instance_config["path_user"]);
$cfv = cl($_instance_config, $pmv);
$vcv = e2_load_settings_from_user_folder_($ccv);
if (
count(
$vfv = AeFileManager::getPathsWithNoWritePermissions(
$cfv["path_user"],
$cfv["path_media"]
)
) > 0
) {
$mq = array_merge($mq, $vfv);
continue;
}
if (Log::$a) {
__log(
'User with key "' .
$pmv .
'" has path "' .
$cfv["path_user"] .
'", ' .
'media path "' .
$cfv["path_media"] .
'"'
);
}
$userDatabaseConfiguration = yl($cfv, $vcv);
if ($cfv["backup_before_update"]) {
rm($userDatabaseConfiguration);
}
cm($userDatabaseConfiguration);
if (Log::$a) {
__log(
'User has migrateable database configuration "' .
$userDatabaseConfiguration .
'"'
);
}
if (@$wmv[$userDatabaseConfiguration->getTablesKeyString()]) {
if (Log::$a) {
__log("Marked as already migrated, will skip");
}
} else {
$databaseConfigurationsToMigrate[
$userDatabaseConfiguration->getTablesKeyString()
] = $userDatabaseConfiguration;
}
AeFileManager::forceUserDirectories($cfv["path_user"]);
AeFileManager::forceMediaDirectories($cfv["path_media"]);
bq($cfv["path_user"] . CACHES_DIRNAME . "*");
if ($ynv < 3354) {
@rename(
$cfv["path_media"] . "pictures/userpics/",
AVATARS_DIRNAME
);
@unlink($cfv["path_user"] . "password-reset.txt");
}
if ($ynv < 3949) {
@unlink($cfv["path_user"] . "indexing.psa");
}
if ($ynv < 4113) {
if (Log::$a) {
__log(
"Fix incorrect filename extensions for thumbs (must be jpg) {"
);
}
$bfv = $cfv["path_media"] . THUMBNAILS_DIRNAME;
foreach (["png", "gif", "webp"] as $yfv) {
foreach (glob($bfv . "*." . $yfv) as $od) {
$nfv = md($od, "jpg");
if (Log::$a) {
__log("Rename " . $od . " to " . $nfv);
}
if (is_file($nfv) or !@rename($od, $nfv)) {
if (Log::$a) {
__log("File exists, unlink " . $od);
}
@unlink($od);
}
}
}
if (Log::$a) {
__log("}");
}
}
foreach (p3() as $ud) {
if (is_file($cfv["path_user"] . $ud)) {
rename(
$cfv["path_user"] . $ud,
$cfv["path_media"] . USERPIC_DIRNAME . $ud
);
}
}
if ($umv) {
ld($cfv["path_user"]);
}
}
if (count($mq) > 0) {
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--fix-permissions"],
"text" =>
"<p>" .
$_strings["gs--fix-permissions"] .
"</p>" .
gb(array_unique($mq)),
"button" => $_strings["fb--retry"],
]),
];
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log(
"Migrate " .
count($databaseConfigurationsToMigrate) .
" database table set(s), namely:"
);
}
$k3 = 0;
foreach (
$databaseConfigurationsToMigrate
as $databaseConfigurationToMigrate
) {
if (Log::$a) {
__log(
++$k3 .
'. "' .
$databaseConfigurationToMigrate->getTablesKeyString() .
'"'
);
}
}
$k3 = 0;
foreach (
$databaseConfigurationsToMigrate
as $databaseConfigurationToMigrate
) {
if (Log::$a) {
__log(
"Prepage for migratation " .
++$k3 .
"/" .
count($databaseConfigurationsToMigrate) .
":"
);
}
gn($databaseConfigurationToMigrate);
}
$k3 = 0;
foreach (
$databaseConfigurationsToMigrate
as $databaseConfigurationToMigrate
) {
if (Log::$a) {
__log(
"Migrate " .
++$k3 .
"/" .
count($databaseConfigurationsToMigrate) .
":"
);
}
wn($databaseConfigurationToMigrate);
$wmv[$databaseConfigurationToMigrate->getTablesKeyString()] = true;
@e3(INSTANCE_DIR . "migration.psa", serialize($wmv));
if ($umv) {
wd($databaseConfigurationToMigrate);
}
}
} catch (AeMySQLCannotConnectException $e) {
if (Log::$a) {
__log("Aborting: cannot connect");
}
if (Log::$a) {
__log($e->getMessage());
}
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--update-cancelled"],
"text" =>
"<p>" . $_strings["er--cannot-connect-to-db"] . "</p>",
]),
];
} catch (AeMySQLNotFoundException $e) {
if (Log::$a) {
__log("Aborting: database not found");
}
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--update-cancelled"],
"text" => "<p>" . $_strings["er--cannot-find-db"] . "</p>",
]),
];
} catch (AeMySQLTooOldException $e) {
if (Log::$a) {
__log("Aborting: " . $_db["software"] . " too old");
}
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--update-cancelled"],
"text" =>
"<p>" .
e2l_get_string("gs--dbs-version-too-old", [
"dbs" => $_db["software"],
"dbv" => $_db["version"],
"minmysql" => E2_MINIMUM_MYSQL,
"minmariadb" => E2_MINIMUM_MARIADB,
"aegearelease" => lq(E2_VERSION),
]) .
"</p>",
]),
];
} catch (AeMySQLNotMigrateableException $e) {
if (Log::$a) {
__log("Aborting: not migrateable");
}
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--update-cancelled"],
"text" =>
"<p>" . $_strings["gs--update-db-incomplete"] . "</p>",
]),
];
} catch (AeMySQLNoDataException $e) {
if (Log::$a) {
__log("Aborting: no data in database");
}
return [
"stub" => ps("generic", [
"heading" => $_strings["pt--update-cancelled"],
"text" =>
"<p>" .
$_strings["gs--update-db-no-data-configure-or-reinstall"] .
"</p>",
]),
];
} finally {
@unlink(INSTANCE_DIR . "updating.psa");
}
@unlink(INSTANCE_DIR . "migration.psa");
if (Log::$a) {
__log("Update completed");
}
$se = nn(E2_VERSION);
return [
"status" => "success",
"from-release" => $jmv,
"to-release" => $hmv,
"instance" => $se,
];
}
function aq(AeDatabaseConfiguration $databaseConfiguration)
{
$mfv = 0;
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
am(
$databaseConfiguration,
"SELECT MAX(`SubsetID`) MaxSubsetID " .
"FROM `" .
$databaseConfiguration->getPrefix() .
$l2 .
"`"
);
$h3 = qm();
$mfv = max($mfv, $h3[0]["MaxSubsetID"]);
}
return $mfv + 1;
}
function qq()
{
$ffv = ini_get("max_execution_time") + 1;
$dfv = @unserialize(file_get_contents(INSTANCE_DIR . "updating.psa"));
if (!is_array($dfv)) {
$dfv = [];
}
if (isset($dfv["locktime"]) and $dfv["locktime"] >= time() - $ffv) {
return true;
}
$dfv["locktime"] = time();
@e3(INSTANCE_DIR . "updating.psa", serialize($dfv));
return false;
}
function lq($x3)
{
$name = "2.6 orearlier";
if ($x3 >= 3119) {
$name = "2.6";
}
if ($x3 >= 3201) {
$name = "2.7b";
}
if ($x3 >= 3225) {
$name = "2.7b2";
}
if ($x3 >= 3239) {
$name = "2.7";
}
if ($x3 >= 3254) {
$name = "2.8a";
}
if ($x3 >= 3335) {
$name = "2.8b";
}
if ($x3 >= 3354) {
$name = "2.8b2";
}
if ($x3 >= 3364) {
$name = "2.8";
}
if ($x3 >= 3382) {
$name = "2.8 SP1";
}
if ($x3 >= 3386) {
$name = "2.8 SP2";
}
if ($x3 >= 3445) {
$name = "2.9a2";
}
if ($x3 >= 3492) {
$name = "2.9a4";
}
if ($x3 >= 3520) {
$name = "2.9b";
}
if ($x3 >= 3543) {
$name = "2.9b2";
}
if ($x3 >= 3553) {
$name = "2.9";
}
if ($x3 >= 3559) {
$name = "2.9 SP1";
}
if ($x3 >= 3565) {
$name = "2.9 SP2";
}
if ($x3 >= 3572) {
$name = "2.9 SP3";
}
if ($x3 >= 3576) {
$name = "2.9 SP4";
}
if ($x3 >= 3733) {
$name = "2.10a";
}
if ($x3 >= 3753) {
$name = "2.10a2";
}
if ($x3 >= 3783) {
$name = "2.10a3";
}
if ($x3 >= 3788) {
$name = "2.10";
}
if ($x3 >= 3805) {
$name = "2.10 SP1";
}
if ($x3 >= 3820) {
$name = "2.10 SP2";
}
if ($x3 >= 3831) {
$name = "2.10 SP3";
}
if ($x3 >= 3849) {
$name = "2.10 SP4";
}
if ($x3 >= 3860) {
$name = "2.10 SP5";
}
if ($x3 >= 3874) {
$name = "2.10 SP6";
}
if ($x3 >= 4034) {
$name = "11.0a";
}
if ($x3 >= 4045) {
$name = "11.0a2";
}
if ($x3 >= 4065) {
$name = "11.0b";
}
if ($x3 >= 4066) {
$name = "11.0b2";
}
if ($x3 >= 4079) {
$name = "11.0";
}
if ($x3 >= 4098) {
$name = "11.1";
}
if ($x3 >= 4116) {
$name = "11.2";
}
if ($x3 >= 4134) {
$name = "11.3";
}
return $name;
}
$_url_map = [
"@retrieve:url" => "e2://e2s_retrieve",
"@instantiate:version" => "e2://e2s_instantiate",
"@notify" => "e2://e2s_notify",
"@info" => "e2://e2m_info",
"" => "e2://e2m_frontpage?page=1",
":page" => "e2://e2m_frontpage",
"rss" => "e2://e2m_rss",
"json" => "e2://e2m_json",
"sitemap.xml" => "e2://e2m_sitemap_xml",
":year" => "e2://e2m_year",
":year/:month" => "e2://e2m_month",
":year/:month/:day" => "e2://e2m_day",
"all" => "e2://e2m_everything",
":note" => "e2://e2m_note?is_published=1&preview-key=0",
":note/:preview" => "e2://e2m_note?is_published=1",
":note/edit" => "e2://e2m_note_edit?is_published=1",
":note/favourite" => "e2://e2s_note_flag_favourite?is_published=1&value=1",
":note/unfavourite" =>
"e2://e2s_note_flag_favourite?is_published=1&value=0",
":note/show" => "e2://e2s_note_flag?is_published=1&flag=IsVisible&value=1",
":note/hide" => "e2://e2s_note_flag?is_published=1&flag=IsVisible&value=0",
":note/discuss" =>
"e2://e2s_note_flag?is_published=1&flag=IsCommentable&value=1",
":note/quiet" =>
"e2://e2s_note_flag?is_published=1&flag=IsCommentable&value=0",
":note/withdraw" => "e2://e2m_note_withdraw?is_published=1",
":note/json" => "e2://e2m_note_json",
":note/broadcast" => "e2://e2m_note_broadcast",
":note/read" => "e2://e2m_note_read",
":note/delete" => "e2://e2m_note_delete?is_published=1",
":note/format/:formatter" => "e2://e2m_note_use_formatter?is_published=1",
":note/:unsubscr" => "e2://e2m_unsubscribe?is_published=1",
":note/:comnum" => "e2://e2m_comment",
":note/:comnum/edit" => "e2://e2m_comment_edit",
":note/:comnum/important" =>
"e2://e2s_comment_flag_ajax?flag=IsFavourite&value=1",
":note/:comnum/usual" =>
"e2://e2s_comment_flag_ajax?flag=IsFavourite&value=0",
":note/:comnum/replace" =>
"e2://e2s_comment_flag_ajax?flag=IsVisible&value=1",
":note/:comnum/remove" =>
"e2://e2s_comment_flag_ajax?flag=IsVisible&value=0",
":note/:comnum/spam" => "e2://e2m_comment_flag?flag=IsSpamSuspect&value=1",
":note/:comnum/good" => "e2://e2m_comment_flag?flag=IsSpamSuspect&value=0",
":note/:comnum/wipe" => "e2://e2m_comment_delete",
":note/:comnum/reply/edit" => "e2://e2m_comment_reply",
":note/:comnum/reply/important" =>
"e2://e2s_comment_flag_ajax?flag=IsReplyFavourite&value=1",
":note/:comnum/reply/usual" =>
"e2://e2s_comment_flag_ajax?flag=IsReplyFavourite&value=0",
":note/:comnum/reply/replace" =>
"e2://e2s_comment_flag_ajax?flag=IsReplyVisible&value=1",
":note/:comnum/reply/remove" =>
"e2://e2s_comment_flag_ajax?flag=IsReplyVisible&value=0",
":note/:comnum/reply/delete" => "e2://e2m_comment_reply_delete",
"drafts" => "e2://e2m_drafts?page=1",
"drafts-:page" => "e2://e2m_drafts",
"drafts/:draft" => "e2://e2m_note?is_published=0&preview-key=0",
"drafts/:draft/:preview" => "e2://e2m_note?is_published=0",
"drafts/:draft/edit" => "e2://e2m_note_edit?is_published=0",
"drafts/:draft/delete" => "e2://e2m_note_delete?is_published=0",
"drafts/:draft/format/:formatter" =>
"e2://e2m_note_use_formatter?is_published=0",
"sources" => "e2://e2m_sources",
"sources/:source/trust" => "e2://e2m_source_trust",
"sources/:source/premoderate" => "e2://e2m_source_premoderate",
"sources/:source/ban" => "e2://e2m_source_ban",
"sources/:source/forget" => "e2://e2m_source_forget",
"tags" => "e2://e2m_tags",
"tags/:tag" => "e2://e2m_tag?page=1",
"tags/:tag/:page" => "e2://e2m_tag",
"tags/:tag/rss" => "e2://e2m_tag_rss",
"tags/:tag/json" => "e2://e2m_tag_json",
"tags/:tag/edit" => "e2://e2m_tag_edit",
"tags/:tag/delete" => "e2://e2m_tag_delete",
"tags/:tag/pin" => "e2://e2s_tag_flag_ajax?flag=IsFavourite&value=1",
"tags/:tag/unpin" => "e2://e2s_tag_flag_ajax?flag=IsFavourite&value=0",
"selected" => "e2://e2m_favourites?page=1",
"selected/:page" => "e2://e2m_favourites",
"hot" => "e2://e2m_most_commented",
"popular" => "e2://e2m_popular",
"untagged" => "e2://e2m_untagged?page=1",
"untagged/:page" => "e2://e2m_untagged",
"calendar" => "e2://e2m_calendar",
"found" => "e2://e2m_found&query=",
"found/:query" => "e2://e2m_found",
"new" => "e2://e2m_write",
"settings" => "e2://e2m_settings",
"settings/underhood" => "e2://e2m_underhood",
"settings/underhood/build" => "e2://e2s_post_service?service=build",
"settings/underhood/sync" => "e2://e2s_post_service?service=sync",
"settings/underhood/checklist-reset" =>
"e2://e2s_post_service?service=checklist-reset",
"settings/underhood/log" => "e2://e2s_post_service?service=log",
"settings/underhood/unlog" => "e2://e2s_post_service?service=unlog",
"settings/underhood/migrate" => "e2://e2s_post_service?service=migrate",
"settings/underhood/verify" => "e2://e2s_post_service?service=verify",
"settings/underhood/backup" => "e2://e2s_dump",
"settings/underhood/index" => "e2://e2s_bsi_step",
"settings/underhood/reindex" => "e2://e2s_reindex",
"settings/database" => "e2://e2m_database",
"settings/password" => "e2://e2m_password?recovery-key=",
"settings/password-reset" => "e2://e2m_password_reset",
"settings/password/:reset" => "e2://e2m_password",
"settings/timezone" => "e2://e2m_timezone",
"settings/sessions" => "e2://e2m_sessions",
"settings/theme-preview" => "e2://e2m_theme_preview?theme=",
"settings/theme-preview/:theme" => "e2://e2m_theme_preview",
"settings/get-backup" => "e2://e2m_get_backup",
"sign-in" => "e2://e2m_sign_in",
"sign-out" => "e2://e2m_sign_out",
"sign-in/:provider" => "e2://e2m_gip_sign_in",
"sign-out/:provider" => "e2://e2m_gip_sign_out",
"sign-in-done/:provider" => "e2://e2m_gip_sign_in_callback",
"@ajax/::" => "e2://e2j_::",
"@actions/::" => "e2://e2s_::",
];
$_url_chunks = [
"\:page" => "page\-(?P<page>\d+)",
"\:year" => "(?P<year>\d{4})",
"\:month" => "(?P<month>\d{1,2})",
"\:day" => "(?P<day>\d{1,2})",
"\:note" => [
"all\/(?P<alias>[-a-zA-Z0-9]+)",
"(?P<year>\d{4})\/(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<day_number>\d+)",
],
"\:draft" => [
"(?P<oalias2>[-a-zA-Z0-9]+)\/(?P<draft2>\d+)",
"(?P<oalias>[-a-zA-Z0-9]+)",
"-\/(?P<draft>\d+)",
],
"\:comnum" => "comment\-(?P<comment_number>[0-9]+)",
"\:file" => "(?P<file>.*?)",
"\:tag" => "(?P<tag_alias>[-a-zA-Z0-9,]+)",
"\:query" => "(?P<query>.*?)",
"\:provider" => "(?P<provider>.*?)",
"\:version" => "\:(?P<version>\d+)",
"\:source" => "\:(?P<source>.*?)",
"\:picture" => "\:(?P<picture>.*?)",
"\:unsubscr" =>
"unsubscribe\:(?P<unsubscribe_email>.+?)\:(?P<unsubscribe_key>[0-9a-f]{32})",
"\:reset" => "reset\:(?P<recovery_key>[0-9a-f]{40})",
"\:formatter" => "(?P<formatter>.*?)",
"\:alias" => "(?P<newalias>[-a-zA-Z0-9]+)",
"\:preview" => "preview\:(?P<preview_key>[0-9a-f]{32})",
"\:theme" => "(?P<theme>[-a-zA-Z0-9]+)",
"\:source" => "(?P<source>\d+)",
"\:url" => "\:(?P<url>[a-zA-Z0-9\=\/\\\+\-\_\,]+)",
];
$_url_autoredirects = [
'/^favo(?:u?)rites(\~.+)?$/i' => 'selected\\1',
"/^favo(?:u?)rites\/(.+)/i" => 'selected/\\1',
'/^keywords$/i' => "tags",
"/^keywords\/(.*)/i" => 'tags/\\1',
'/^everything$/i' => "all",
"/^search\/(.+)/i" => 'found/\\1',
'/^(\d{4}\/\d{1,2}\/\d{1,2}\/\d+)\/comments(\/?)$/i' => '\\1',
"/^\~(\d+)/i" => 'page-\\1',
"/\/?\~(\d+)/i" => '/page-\\1',
];
function zq()
{
global $_config;
$sfv = [
"result",
"url",
"entity",
"entity-id",
"overwrite",
"data",
"src",
"ord",
];
if ($_config["raw_template_data_with_param"]) {
$sfv[] = "raw";
}
return $sfv;
}
function kq($url)
{
global $_url_autoredirects;
$url = preg_replace(
array_keys($_url_autoredirects),
array_values($_url_autoredirects),
$url
);
if (preg_match("/^([0-9]+)[.-]([0-9]+)[.-]([0-9]+)(.*)/", $url, $v6)) {
if (2 == strlen($v6[3])) {
$v6[3] = "20" . $v6[3];
}
return $v6[3] . "/" . $v6[2] . "/" . $v6[1] . $v6[4];
}
if (preg_match('/^tags\-rss\/(.*?)\/?$/', $url, $v6)) {
$gv = substr($v6[1], strrpos($v6[1], "/") + 1);
return "tags/" . $gv . "/rss/";
}
return $url;
}
function xq()
{
static $afv = false;
global $__synthetic_urls, $_config;
if ($afv) {
return;
}
$qfv = $_config["url_composition"];
$__synthetic_urls = false;
if ($qfv == "synthetic") {
$__synthetic_urls = true;
}
if ($qfv == "auto") {
if (function_exists("apache_get_modules")) {
if (in_array("mod_rewrite", apache_get_modules())) {
$__synthetic_urls = true;
}
}
}
if (getenv("E2_SYNTH_URLS")) {
$__synthetic_urls = (bool) getenv("E2_SYNTH_URLS");
}
if (isset($_SERVER["E2_SYNTH_URLS"])) {
$__synthetic_urls = (bool) $_SERVER["E2_SYNTH_URLS"];
}
$afv = true;
}
function eq($candy, $parameters = [])
{
global $_url_map, $_url_chunks, $_config, $__synthetic_urls;
$lfv = array_flip($_url_map);
$url = AeEnv::$p;
$zfv = "e2://" . $candy;
if (array_key_exists("page", $parameters)) {
$parameters["page"] = (int) $parameters["page"];
}
if (array_key_exists("day", $parameters)) {
$parameters["day"] = str_pad(
(int) $parameters["day"],
2,
"0",
STR_PAD_LEFT
);
}
if (array_key_exists("month", $parameters)) {
$parameters["month"] = str_pad(
(int) $parameters["month"],
2,
"0",
STR_PAD_LEFT
);
}
if ($parameters) {
$zfv .= "?";
$kfv = [];
$xfv = [];
foreach ($parameters as $yn => $vv) {
if ($yn == "*note") {
$xfv[] = $yn;
$kfv[] = jq($vv);
}
if ($yn == "*tags") {
$xfv[] = $yn;
$kfv[] = hq($vv);
}
if ($yn == "*tag") {
$xfv[] = $yn;
$kfv[] = hq([$vv]);
}
}
foreach ($xfv as $yn) {
unset($parameters[$yn]);
}
foreach ($kfv as $efv) {
$parameters = array_merge($parameters, $efv);
}
foreach ($parameters as $yn => $vv) {
if (@$yn[0] != "_") {
$zfv .= $yn . ($vv !== true ? "=" . urlencode($vv) : "") . "&";
}
}
$zfv = substr($zfv, 0, -1);
}
if (array_key_exists($zfv, $lfv)) {
if ($lfv[$zfv] !== "") {
if (!$__synthetic_urls) {
$url .= "?go=";
}
$url .= $lfv[$zfv];
if (!in_array(substr($lfv[$zfv], -4), [".txt", ".xml"])) {
$url .= "/";
}
}
return $url;
} else {
$jfv = false;
foreach ($lfv as $hfv => $gfv) {
$wfv = $hfv;
$wfv = preg_quote($wfv, "/");
$ufv = parse_url($hfv);
$ifv = $ufv["host"];
$ofv = parse_url($zfv);
if (strstr($hfv, "::")) {
$pfv = $ofv["scheme"] . "://" . $ofv["host"];
$wfv = str_replace("\:\:", "(.*)", $wfv);
$wfv = "/^" . $wfv . '$/s';
if (preg_match($wfv, $pfv, $v6)) {
$pnv = str_replace("::", $v6[1], $gfv);
$pnv = str_replace("_", "-", $pnv);
$e2_ = false;
if (array_key_exists("query", $ofv)) {
$e2_ = $ofv["query"];
}
if ($__synthetic_urls and $e2_) {
$url .= $pnv . "/?" . $e2_;
} elseif ($__synthetic_urls) {
$url .= $pnv . "/";
} elseif ($e2_) {
$url .= "?go=" . $pnv . "/?" . $e2_;
} else {
$url .= "?go=" . $pnv . "/";
}
return $url;
}
}
$c2v = false;
if ($candy === $ifv) {
$jfv = true;
if ((string) @$ufv["query"] !== "") {
$v2v = explode("&", $ufv["query"]);
foreach ($v2v as $b2v) {
list($yn, $vv) = explode("=", $b2v);
$vv = urldecode($vv);
$yn = str_replace("_", "-", $yn);
if (
array_key_exists($yn, $parameters) and
$parameters[$yn] != $vv
) {
$c2v = true;
break;
}
}
}
if (!$c2v) {
if (preg_match_all("/\:[\-a-z]+/i", $gfv, $v6)) {
foreach ($v6[0] as $y2v) {
$n2v = $_url_chunks["\\" . $y2v];
if (!is_array($n2v)) {
$n2v = [$n2v];
}
$m2v = $n2v[0];
foreach ($n2v as $m2v) {
$f2v = "/\(\?P\<(.*?)\>.*?\)/";
$d2v = true;
if (@preg_match_all($f2v, $m2v, $v6)) {
$v6 = $v6[1];
$d2v = true;
for ($gb = 0; $gb < count($v6); ++$gb) {
if (
!array_key_exists(
str_replace("_", "-", $v6[$gb]),
$parameters
) or
$parameters[
str_replace("_", "-", $v6[$gb])
] ===
""
) {
$d2v = false;
break;
}
}
}
if (!$d2v) {
continue;
}
$s2v = @preg_replace_callback(
$f2v,
function ($v6) use ($parameters) {
return $parameters[
str_replace("_", "-", $v6[1])
];
},
$m2v
);
$s2v = stripslashes($s2v);
$a2v = str_replace($y2v, $s2v, $gfv);
break;
}
$gfv = @$a2v;
}
}
$q2v = [];
if ($gfv) {
if ($__synthetic_urls) {
$url .= $gfv . "/";
} else {
$q2v[] = "go=" . $gfv . "/";
}
}
if (@$parameters["raw"] === true) {
if ($_config["raw_template_data_with_param"]) {
$q2v[] = "raw";
}
}
if (count($q2v)) {
$url .= "?" . implode("&", $q2v);
}
return $url;
}
}
}
if ($jfv) {
return $url;
} else {
die("Cannot compose url for candy " . $candy);
}
}
}
function rq($url = null)
{
global $_url_map, $_url_chunks, $_current_url;
if (Log::$a) {
__log('Resolve request "' . $url . '" {');
}
xq();
$url = trim($url, "/");
$url = kq($url);
$parameters = [];
$zfv = "";
foreach ($_url_map as $l2v => $hfv) {
$z2v = $l2v;
$z2v = preg_quote($z2v, "/");
if (strstr($l2v, "::")) {
$z2v = str_replace("\:\:", "(.*)", $z2v);
$z2v = "/^" . $z2v . '$/s';
if (preg_match($z2v, $url, $v6)) {
$k2v = str_replace("-", "_", $v6[1]);
$zfv = str_replace("::", $k2v, $hfv);
}
} elseif (strstr($l2v, ":")) {
$x2v = [];
foreach ($_url_chunks as $k3 => $x3) {
if (is_array($x3)) {
$x2v[$k3] = "(?:(?:" . implode(")|(?:", $x3) . "))";
} else {
$x2v[$k3] = $x3;
}
}
$z2v = str_replace(array_keys($x2v), array_values($x2v), $z2v);
$z2v = "/^" . $z2v . '$/s';
if (preg_match($z2v, $url, $v6)) {
$zfv = $hfv;
foreach ($v6 as $yn => $vv) {
if (!is_numeric($yn)) {
$yn = str_replace("_", "-", $yn);
$parameters[$yn] = $vv;
}
}
}
} else {
if ($l2v == $url) {
$zfv = $hfv;
break;
}
}
}
if ($zfv) {
$e2v = true;
} else {
$e2v = false;
$zfv = "e2://e2m_error404";
}
if (!$zfv) {
$zfv = "e2://e2m_error404";
}
$ofv = parse_url($zfv);
$candy = $ofv["host"];
if ((string) @$ofv["query"] !== "") {
$v2v = explode("&", $ofv["query"]);
foreach ($v2v as $b2v) {
list($yn, $vv) = explode("=", $b2v);
$vv = urldecode($vv);
$yn = str_replace("_", "-", $yn);
$parameters[$yn] = $vv;
}
}
foreach ($_GET as $yn => $vv) {
if (in_array($yn, zq(), true)) {
($parameters[$yn] = (string) $vv) or ($parameters[$yn] = true);
}
}
$vb = false;
if ($e2v) {
$_current_url = AeEnv::$h . "://" . AeEnv::$j . $_SERVER["REQUEST_URI"];
wq($candy, $parameters);
if (is_callable($candy)) {
$vb = [$candy, $parameters];
} else {
$vb = [null, []];
}
} else {
$vb = [null, []];
}
if (Log::$a) {
$r2v = "";
if (count($vb[1]) > 0) {
$r2v = print_r($vb[1], true);
$r2v = substr($r2v, 8, -2);
$r2v = " " . trim($r2v);
$r2v = preg_replace('/^.*?$/smu', ' $0', $r2v);
$r2v = " with parameters:" . "\r\n" . $r2v;
}
__log('Resolved to candy "' . $vb[0] . '"' . $r2v);
}
if (Log::$a) {
__log("}");
}
return $vb;
}
function jq($zy)
{
if (!isset($zy["IsPublished"])) {
throw new LogicException(
"Cannot compose parameters from noterec without IsPublished"
);
return [];
}
if (!$zy["IsPublished"]) {
$parameters["is-published"] = 0;
if ($zy["OriginalAlias"] === "") {
$parameters["draft"] = $zy["ID"];
} elseif (tb($zy["OriginalAlias"]) == 1) {
$parameters["oalias"] = $zy["OriginalAlias"];
} else {
$parameters["draft2"] = $zy["ID"];
$parameters["oalias2"] = $zy["OriginalAlias"];
}
return $parameters;
}
$parameters["is-published"] = 1;
$dy = b();
$ay = "n" . $zy["ID"];
$t2v = $dy[$ay];
if (isset($zy["__force_ymdn"]) and (string) $zy["OriginalAlias"] === "") {
$ay = "n" . $zy["ID"] . "-ymdn";
if (array_key_exists($ay, $dy)) {
$t2v = $dy[$ay];
}
}
if (
preg_match(
"/(?P<year>\d{4})\/(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<day_number>\d+)/",
$t2v,
$v6
)
) {
$parameters["year"] = $v6["year"];
$parameters["month"] = $v6["month"];
$parameters["day"] = $v6["day"];
$parameters["day-number"] = $v6["day_number"];
} else {
$parameters["alias"] = $t2v;
}
return $parameters;
}
function hq($jb)
{
$j2v = $parameters = [];
foreach ($jb as $wb) {
$j2v[] = b()["t" . $wb["ID"]];
}
if (count($j2v)) {
$parameters["tag-alias"] = implode(",", $j2v);
}
return $parameters;
}
function gq($parameters)
{
if (
(string) @$parameters["alias"] !== "" or
(string) @$parameters["year"] !== "" and
(string) @$parameters["month"] !== "" and
(string) @$parameters["day"] !== "" and
(string) @$parameters["day-number"] !== ""
) {
if ($r = e2_published_noterec_with_parameters_($parameters)) {
if (Log::$a) {
__log(
"Fetched note " .
$r["ID"] .
' "' .
$r["Title"] .
'" as *note'
);
}
$parameters["*note"] = $r;
foreach (["alias", "year", "month", "day", "day-number"] as $h2v) {
if (array_key_exists($h2v, $parameters)) {
unset($parameters[$h2v]);
}
}
}
}
if (
(string) @$parameters["oalias"] !== "" or
(string) @$parameters["draft"] !== "" or
(string) @$parameters["oalias2"] !== "" or
(string) @$parameters["draft2"] !== ""
) {
if ($r = e2_noterec_with_parameters_($parameters)) {
if (Log::$a) {
__log(
"Fetched note " .
$r["ID"] .
' "' .
$r["Title"] .
'" as *note'
);
}
if ((string) @$parameters["oalias"] !== "") {
$parameters["alias"] = $parameters["oalias"];
} elseif ((string) @$parameters["oalias2"] !== "") {
$parameters["alias"] = $parameters["oalias2"];
}
$parameters["*note"] = $r;
foreach (["oalias", "draft", "oalias2", "draft2"] as $h2v) {
if (array_key_exists($h2v, $parameters)) {
unset($parameters[$h2v]);
}
}
}
}
if ((string) @$parameters["tag-alias"] !== "") {
$parameters["*tags"] = e2_tagrecs_with_parameters_($parameters);
if (Log::$a) {
__log(
"Fetched " . count($parameters["*tags"]) . " tag(s) as *tag(s)"
);
}
if (count($parameters["*tags"]) == 1) {
$parameters["*tag"] = $parameters["*tags"][0];
unset($parameters["*tags"]);
if (array_key_exists("tag-alias", $parameters)) {
unset($parameters["tag-alias"]);
}
}
}
return $parameters;
}
function wq($candy, $parameters)
{
global $_config, $_current_url, $_canonical_url;
if (!$_config["force_canonical_urls"]) {
return;
}
if ($candy === "e2m_install") {
return;
}
if ($candy === "e2m_sign_in") {
return;
}
if ($candy === "e2m_error404") {
return;
}
if ($candy === "e2m_gip_sign_in_callback") {
return;
}
if ($candy === "e2s_notify") {
return;
}
if ($candy === "e2j_file_upload") {
return;
}
$_canonical_url = eq($candy, $parameters);
if (Log::$a) {
__log("Params are: " . var_export($parameters, true));
}
if (
$_current_url != $_canonical_url and
urldecode($_current_url) != $_canonical_url
) {
if (Log::$a) {
__log('Used URL "' . $_current_url . '"');
}
if (Log::$a) {
__log('Redirecting to canonical URL "' . $_canonical_url . '"');
}
z1($_canonical_url);
}
}
function uq($g2v)
{
global $_instance_config;
$pmv = str_replace("/", "--", $g2v);
if (substr($pmv, 0, 4) == "www.") {
$pmv = substr($pmv, 4);
}
if (array_key_exists($pmv, $_instance_config["path_user_rewrites"])) {
$pmv = $_instance_config["path_user_rewrites"][$pmv];
}
return $pmv;
}
function iq()
{
static $w2v = null;
if ($w2v !== null) {
return $w2v;
}
$u2v = AeEnv::$server . AeEnv::$w;
if (AeEnv::$u !== (string) "") {
$u2v .= "/" . AeEnv::$u;
}
$w2v = uq($u2v);
return $w2v;
}
function oq($ccv, $i2v)
{
$o2v = $i2v;
$o2v = preg_quote($o2v);
$o2v = str_replace("/", "\/", $o2v);
$o2v = str_replace("%USERKEY%", "(.*?)", $o2v);
$o2v = "/" . $o2v . "/i";
$pmv = "";
if (preg_match($o2v, $ccv, $v6) and array_key_exists(1, $v6)) {
$pmv = $v6[1];
}
return $pmv;
}
function pq($p2v, $pmv)
{
foreach (["path_user", "path_media"] as $cdv) {
if (!array_key_exists($cdv . ".raw", $p2v)) {
$p2v[$cdv . ".raw"] = $p2v[$cdv];
}
if (strpos($p2v[$cdv . ".raw"], "%USERKEY%") !== false) {
$p2v[$cdv] = str_replace("%USERKEY%", $pmv, $p2v[$cdv . ".raw"]);
}
}
return $p2v;
}
function cl($vdv, $pmv)
{
foreach (["path_user", "path_media"] as $cdv) {
if (!array_key_exists($cdv . ".raw", $vdv)) {
$vdv[$cdv . ".raw"] = $vdv[$cdv];
}
if (strpos($vdv[$cdv . ".raw"], "%USERKEY%") !== false) {
$vdv[$cdv] = str_replace("%USERKEY%", $pmv, $vdv[$cdv . ".raw"]);
}
}
$_config = $vdv;
if (is_file($px = $vdv["path_user"] . "config.php")) {
include $px;
$_config += $vdv;
}
return $_config;
}
function vl()
{
global $_instance_config;
if (strpos($_instance_config["path_user"], "%USERKEY%") !== false) {
$bdv = str_replace("%USERKEY%", "*", $_instance_config["path_user"]);
return glob($bdv);
} else {
return [$_instance_config["path_user"]];
}
}
function bl()
{
static $databaseConfiguration = null;
global $settings, $_config;
if ($databaseConfiguration === null) {
$databaseConfiguration = yl($_config, $settings);
}
return $databaseConfiguration;
}
function yl($cfv, $vcv)
{
$icv = null;
$ydv = null;
if (getenv("E2_DB_SERVER")) {
$icv["server"] = getenv("E2_DB_SERVER");
}
if (getenv("E2_DB_USER_NAME")) {
$icv["user_name"] = getenv("E2_DB_USER_NAME");
}
if (getenv("E2_DB_PASSW")) {
$icv["passw"] = getenv("E2_DB_PASSW");
}
if (getenv("E2_DB_NAME")) {
$icv["name"] = getenv("E2_DB_NAME");
}
if ($icv !== null) {
$ydv = "environment";
if (Log::$a) {
__log(
"Database configuration found in Environment, wont look elsewhere"
);
}
} else {
if (Log::$a) {
__log("No database configuration found in Environment");
}
$icv = $cfv["db"];
if ($icv !== null) {
$ydv = "config";
if (Log::$a) {
__log(
"Database configuration found in Config, wont look elsewhere"
);
}
} else {
if (Log::$a) {
__log("No database configuration found in Config");
}
if (array_key_exists("db", $vcv)) {
$ydv = "settings";
if (Log::$a) {
__log("Database configuration found in Settings");
}
$icv = $vcv["db"];
} else {
if (Log::$a) {
__log("No database configuration found anywhere");
}
}
}
}
if ($icv === null) {
return null;
}
$databaseConfiguration = new AeDatabaseConfiguration(
$ydv,
$cfv["path_user"] . BACKUP_DIRNAME,
$icv["server"],
$icv["user_name"],
$icv["passw"],
$icv["name"],
$cfv["db_table_prefix"],
$cfv["db_table_subset"]
);
return $databaseConfiguration;
}
function nl($ndv, $mdv = false)
{
$fdv = "";
$lz = strlen($ndv);
for ($gb = 0; $gb < 256; ++$gb) {
$ddv[$gb] = 0;
$sdv = $gb;
while ($sdv & 0x00000080) {
$sdv <<= 1;
++$ddv[$gb];
}
}
for ($gb = 0xd090; $gb <= 0xd0bf; $gb++) {
$adv[$gb] = chr(($gb & 0x000000ff) + 48);
}
for ($gb = 0xd180; $gb <= 0xd18f; $gb++) {
$adv[$gb] = chr(($gb & 0x000000ff) + 112);
}
$adv[0xd081] = "\xa8";
$adv[0xd191] = "\xb8";
$adv[0xc299] = "\x99";
$adv[0xc2a9] = "\xa9";
$adv[0xc2ae] = "\xae";
$adv[0xc2ab] = "\xab";
$adv[0xc2bb] = "\xbb";
$adv[0xc2a0] = "\xa0";
$gb = 0;
while ($gb < $lz) {
$qdv = $ndv[$gb];
$ldv = ord($qdv);
if ($ddv[$ldv] == 0) {
$fdv .= $qdv;
++$gb;
} elseif ($ddv[$ldv] == 2) {
$zdv = $adv[($ldv << 8) | ord($ndv[$gb + 1])];
$fdv .=
$zdv != null
? $zdv
: ($mdv
? e2utf8__unformat_htmlentity(ml(substr($ndv, $gb, 2)))
: "?");
$gb += 2;
} else {
$kdv = substr($ndv, $gb, $ddv[$ldv]);
if ($kdv == "\xe2\x84\x96") {
$fdv .= "\xb9";
} elseif ($kdv == "\xe2\x80\x93") {
$fdv .= "\x96";
} elseif ($kdv == "\xe2\x80\x94") {
$fdv .= "\x97";
} elseif ($kdv == "\xe2\x80\x98") {
$fdv .= "\x91";
} elseif ($kdv == "\xe2\x80\x99") {
$fdv .= "\x92";
} elseif ($kdv == "\xe2\x80\x9a") {
$fdv .= "\x82";
} elseif ($kdv == "\xe2\x80\x9c") {
$fdv .= "\x93";
} elseif ($kdv == "\xe2\x80\x9d") {
$fdv .= "\x94";
} elseif ($kdv == "\xe2\x80\x9e") {
$fdv .= "\x84";
} elseif ($kdv == "\xe2\x80\xa6") {
$fdv .= "\x85";
} elseif ($kdv == "\xe2\x80\xb9") {
$fdv .= "\x8b";
} elseif ($kdv == "\xe2\x80\xba") {
$fdv .= "\x9b";
} elseif ($kdv == "\xe2\x82\xac") {
$fdv .= "\x88";
} elseif ($kdv == "\xe2\x84\xa2") {
$fdv .= "\x99";
} else {
$fdv .= $mdv ? e2utf8__unformat_htmlentity(ml($kdv)) : "?";
}
$gb += $ddv[$ldv];
}
}
return $fdv;
}
function ml($nvv)
{
$xdv = "";
$lz = strlen($nvv);
for ($gb = 0; $gb < $lz; ++$gb) {
$xdv .= preg_replace("/^1*0/", "", decbin(ord($nvv[$gb])));
}
return "&#" . bindec($xdv) . ";";
}
if (!BUILT) {
include "builder.php";
}
if (version_compare(PHP_VERSION, E2_MINIMUM_PHP) < 0) {
die(
"PHP version must be " .
E2_MINIMUM_PHP .
" or later, you are running " .
PHP_VERSION
);
}
if (!function_exists("getimagesize")) {
die("Function getimagesize is not defined, php_gd not installed?");
}
if (!extension_loaded("gd")) {
die("Extension gd not loaded, php_gd not installed?");
}
if (!function_exists("mb_internal_encoding")) {
die(
"Function mb_internal_encoding is not defined, php_mbstring not installed?"
);
}
if (!class_exists("PDO")) {
die("Class PDO is not defined installed, PDO not installed?");
}
if (!in_array("mysql", PDO::getAvailableDrivers())) {
die('Required PDO driver "mysql" not installed');
}
if (!is_file($px = "system/default/config.php")) {
die("File not found: " . $px);
}
error_reporting(E_ALL);
setlocale(LC_CTYPE, "ru_RU.UTF");
mb_internal_encoding("UTF-8");
date_default_timezone_set("GMT");
mysqli_report(MYSQLI_REPORT_OFF);
if (version_compare(PHP_VERSION, "7.0") < 0) {
error_reporting(E_ALL & ~E_STRICT);
}
ini_set("pcre.jit", "0");
include $px;
$_system_default_config = $_config;
foreach (["instance/", $_config["path_user"]] as $edv) {
if (is_dir($rdv = $edv)) {
if (is_file($px = $rdv . "config.php")) {
include $px;
$_config += $_system_default_config;
}
break;
}
}
$_instance_config = $_config;
define("INSTANCE_DIR", $rdv);
AeEnv::examine($_SERVER);
$_config = cl($_instance_config, iq());
define("USER_DIR", $_config["path_user"]);
define("USER_URLPATH", "user/");
AeEnv::setPrefersHTTPS($_config["force_https"]);
AeEnv::setPreferredServer($_config["preferred_domain_name"]);
AeFileManager::setInstancePath(INSTANCE_DIR);
AeFileManager::setUserPath($_config["path_user"]);
AeFileManager::setMediaPath($_config["path_media"]);
$_stopwatch = dq($_stopwatch);
spl_autoload_register("rd");
spl_autoload_register("dy");
spl_autoload_register("uy");
an();
function e2()
{
global $settings,
$content,
$_candy,
$_lang,
$_config,
$_strings,
$_template;
if (!is_dir($_config["path_user"])) {
die("User directory not found: " . $_config["path_user"]);
}
$settings = e2_load_settings_from_user_folder_(USER_DIR);
$_strings = fn_();
if (Log::$a) {
__log(
'Serving the user with key "' .
iq() .
'" ' .
'using directory "' .
$_config["path_user"] .
'"'
);
}
$tdv = serialize($_config);
$tdv = AeEnv::$server . $tdv;
$tdv = serialize(md5($tdv));
$jdv = $_config["path_user"] . "config-hash.psa";
if ($tdv !== (string) @unserialize(file_get_contents($jdv))) {
if (Log::$a) {
__log("Edition or configuration changed, dropping all caches");
}
e2_drop_all_kinds_of_cache();
mn();
if (!@e3($jdv, serialize($tdv))) {
die("Cannot write file: " . $jdv);
}
}
p1();
set_error_handler("wb");
set_exception_handler("y3");
$hdv = new AeRequest($_SERVER, $_GET);
$content = [];
$_candy = $hdv->candy;
$se = yn();
$gdv = true;
$wdv = true;
$gn = ys();
if (
$hdv->requiresInstallation() and
($se === null or bl() === null or !vs())
) {
$gdv = false;
if (!$_config["allow_installer"] or !$_config["allow_db_config"]) {
$content = ps("not-configured");
} elseif (
count(
$mq = AeFileManager::getPathsWithNoWritePermissions(
$_config["path_user"],
$_config["path_media"]
)
) > 0
) {
$content = ps("generic", [
"heading" => $_strings["pt--fix-permissions"],
"text" =>
"<p>" .
$_strings["gs--fix-permissions"] .
"</p>" .
gb(array_unique($mq)),
"button" => $_strings["fb--retry"],
]);
} else {
$hdv->replaceWith("e2m_install");
}
}
if (
empty($content) and
$hdv->requiresVersionMatch() and
E2_VERSION !== $se["version"]
) {
$wdv = false;
if (Log::$a) {
__log("Startup: need to update first");
}
$udv = sq($se["version"]);
if (@$udv["status"] === "success") {
$se = $udv["instance"];
if (ys()) {
hb(
e2l_get_string("gs--updated-successfully", [
"from" => $udv["from-release"],
"to" => $udv["to-release"],
]),
E2E_MESSAGE
);
}
$wdv = true;
} else {
$content = $udv["stub"];
}
}
if (empty($content) and $hdv->requiresSignIn()) {
if (Log::$a) {
__log("Author signed in? " . ($gn ? "Yes" : "No"));
}
if (!$gn) {
$hdv->replaceWith("e2m_sign_in");
if ($hdv->toBeFulfilledByService()) {
z1(eq("e2m_sign_in"));
}
}
}
if (
empty($content) and
!$hdv->allowedInReadOnlyMode() and
$_config["read_only"]
) {
$content = ps("read-only-mode");
$gdv = false;
}
header("X-Powered-By: " . E2_UA_STRING);
header("Content-type: text/html; charset=UTF-8");
if (empty($content)) {
if (!is_callable($hdv->candy)) {
$hdv->replaceWith("e2m_error404");
}
if (Log::$a) {
__log("Candy after clearance: " . $hdv->candy);
}
if ($hdv->shouldSlowDownAJAXResponse() and $_config["dev_slow_ajax"]) {
sleep(1 + 2 * (rand() / getrandmax()));
}
try {
if ($hdv->requiresInstallation()) {
$hdv->parameters = gq($hdv->parameters);
if (Log::$a) {
__log("Call e2_canonize_url for the second time:");
}
wq($hdv->candy, $hdv->parameters);
if (
array_key_exists("is-published", $hdv->parameters) and
$hdv->parameters["is-published"] == "0" and
(string) @$hdv->parameters["*note"]["IsPublished"] == "1"
) {
z1(eq($hdv->candy, $hdv->parameters));
}
}
if (Log::$a) {
__log("Candy call {");
}
$content = call_user_func($hdv->candy, $hdv->parameters);
} catch (AeMySQLException $e) {
if (!$hdv->toBeFulfilledByService()) {
v3($e);
$hdv->parameters = [];
$content["unavailable?"] = true;
} else {
throw $e;
}
}
if (Log::$a) {
__log("}");
}
}
if (!is_array($content)) {
$content = [];
}
if (!array_key_exists("notes", $content)) {
$content["notes"] = [];
}
if (!array_key_exists("tag", $content)) {
$content["tag"] = [];
}
if (!array_key_exists("drafts", $content)) {
$content["drafts"] = [];
}
if (!array_key_exists("comments", $content)) {
$content["comments"] = [];
}
if (!array_key_exists("notes-list", $content)) {
$content["notes-list"] = [];
}
$content["title"] = strip_tags(
ay(htmlspecialchars((string) @$content["title"], ENT_NOQUOTES, "UTF-8"))
);
if (!empty($content["heading"])) {
$content["heading"] = strip_tags(
ay(
htmlspecialchars(
(string) @$content["heading"],
ENT_NOQUOTES,
"UTF-8"
)
)
);
}
$content["language"] = $_lang;
if (!isset($_template)) {
kf();
}
$content["template"]["respond-to-dark-mode?"] =
(array_key_exists("supports_dark_mode", $_template) and
$_template["supports_dark_mode"] and
@(bool) $settings["appearance"]["respond_to_dark_mode"]);
$content["template"]["use-likely-light?"] = $_template["use_likely_light"];
if (!array_key_exists("class", $content)) {
$content["class"] = str_replace(
"_",
"-",
str_replace("e2m_", "", $hdv->candy)
);
}
if ($gdv and $wdv) {
if (Log::$a) {
__log("Stuff for installed engine {");
}
d3("rss", ev(), eq("e2m_rss"));
d3("json", ev(), eq("e2m_json"));
$content["sign-in"] = [
"done?" => (bool) $gn,
"required?" => (bool) $hdv->requiresSignIn(),
"necessary?" => (bool) $hdv->requiresSignIn() && !$gn,
"href" => eq("e2m_sign_in"),
"prompt" => $_strings["gs--need-password"],
"token" => ud(),
];
$content["hrefs"] = ["everything" => eq("e2m_everything")];
if (!array_key_exists("tags", $content)) {
$content["tags"] = da($hdv->parameters);
}
if (!array_key_exists("main-menu", $content)) {
$content["main-menu"] = rn($hdv->parameters, $content["class"]);
}
$content["blog"] = xv();
$content["form-search"] = ad($hdv->parameters);
$content["engine"] = jb();
$content["form-login"] = xs();
if ($content["form-login"] === null) {
unset($content["form-login"]);
}
if (!array_key_exists("summary", $content)) {
if (!empty($settings["meta_description"])) {
$content["summary"] = strip_tags(
ay(
htmlspecialchars(
$settings["meta_description"],
ENT_NOQUOTES,
"UTF-8"
)
)
);
} else {
$content["summary"] = @trim(
strip_tags($content["blog"]["subtitle"])
);
}
}
if (@$settings["appearance"]["show_view_counts"]) {
AeNoteReadCountsProvider::setSQLRequestTemplateToMapIDsToReadCounts(
"SELECT `ID`, `ReadCount` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"]
);
}
foreach ($content["notes"] as $r) {
m2(@$r["format-info"]["links-required"]);
}
if ($gn) {
$content["admin"] = c();
$content["last-modifieds-by-id"] = "{}";
if (@$_COOKIE[x1("local_copies")]) {
$content["last-modifieds-by-id"] = im(
$_COOKIE[x1("local_copies")]
);
}
if ($_config["allow_self_check"]) {
$idv = es();
}
}
if (Log::$a) {
__log("}");
}
}
$content["message"] = ib();
$zu = gf();
$content["meta"] = hn(
$hdv->candy,
$content["notes"],
$content["tag"],
$content["blog"],
$content["pages"]
);
$content["stat"] = jv();
$zu = tf($zu);
echo $zu;
if ($gdv and $wdv and $_SERVER["HTTP_USER_AGENT"] !== E2_UA_STRING) {
if (!kd()) {
if (Log::$a) {
__log("Spawn BSI step");
}
vv(eq("e2s_bsi_step"));
}
if ($_config["allow_self_check"] and !$idv) {
rs();
}
}
if (@$_config["dev_dump_ctree"]) {
ln($content);
}
} ?>
Did this file decode correctly?
Original Code
<?php
$_stopwatch = microtime();
define("E2_VERSION", 4134);
define("E2_RELEASE", "11.3");
define("CACHE", 1);
define("BUILDER_OBFUSCATE", 1);
define("BUILDER_FLATTEN", 1);
define("BUILT", !strstr(__FILE__, "all.php"));
define("E2_RUN_ID", chr(rand(65, 90)));
function e2m_error404()
{
global $_config, $_strings;
if ($_config["try_redirect_to_all"]) {
$c = "all/" . urldecode((string) @$_GET["go"]);
rq($c);
}
header("HTTP/1.1 404 Not found");
$v["class"] = "404";
$v["heading"] = $_strings["pt--page-not-found"];
$v["title"] = $_strings["pt--page-not-found"];
return $v;
}
class AeArbitraryNotesCollectionView
{
private $name = "";
private $isCached = false;
private $hasRun = false;
private $sql = null;
private $currentURL = null;
private $cacheFilename = null;
private $cacheExpiresFilename = null;
private $cacheable = [];
private $viewExpiration = null;
private $notesCTree = null;
private $filterOutIDs = [];
public function __construct($name)
{
$this->name = $name;
}
public function setSQLRequest($sql)
{
$this->sql = $sql;
}
public function setCurrentURL($currentURL)
{
$this->currentURL = $currentURL;
}
public function setCacheFilename($cacheFilename)
{
$this->isCached = true;
$this->cacheFilename = $cacheFilename;
}
public function setCacheExpiresFilename($cacheExpiresFilename)
{
$this->cacheExpiresFilename = $cacheExpiresFilename;
}
public function setViewExpiration($viewExpiration)
{
$this->viewExpiration = $viewExpiration;
}
public function setFilterOutIDs($filterOutIDs)
{
$this->filterOutIDs = $filterOutIDs;
}
public function orderNotesCTreeByVerticality()
{
if (!$this->hasRun) {
$this->run();
}
usort($this->notesCTree, function ($b, $y) {
if (empty($b["images"][0]["verticality"])) {
$n = 0;
} else {
$n = $b["images"][0]["verticality"];
}
if (empty($y["images"][0]["verticality"])) {
$m = 0;
} else {
$m = $y["images"][0]["verticality"];
}
return (int) round(($m - $n) * 10000);
});
}
public function getNotesCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->notesCTree;
}
private function prepareCacheableData()
{
$f = [
"notes-records" => function () {
$d = [];
try {
sm($this->sql, 'get "' . $this->name . '" list');
foreach (qm() as $s) {
if (ff($s) === "public") {
$d[] = $s;
}
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Could not get list from database");
}
}
return $d;
},
];
if ($this->isCached and is_file($this->cacheFilename)) {
($this->cacheable = @unserialize(
file_get_contents($this->cacheFilename)
)) or ($this->cacheable = []);
}
$q = true;
if (!empty($this->cacheExpiresFilename)) {
if ($this->isCached and is_file($this->cacheExpiresFilename)) {
$l = time();
$z = (int) @file_get_contents($this->cacheExpiresFilename);
if (Log::$a) {
__log(
"List expires " .
date("r", $z) .
", now " .
date("r", $l)
);
}
$q = $l < $z;
}
}
$k = false;
foreach ($f as $x => $e_) {
if (!array_key_exists($x, $this->cacheable) or !$q) {
if (Log::$a) {
__log('Build cache: "' . $x . '"');
}
$this->cacheable[$x] = $e_();
$k = true;
} else {
if (Log::$a) {
__log('Retrieved from cache: "' . $x . '"');
}
}
}
if ($this->isCached and $k) {
e3($this->cacheFilename, serialize($this->cacheable));
if ($this->cacheExpiresFilename) {
@e3(
$this->cacheExpiresFilename,
time() + $this->viewExpiration
);
}
}
}
private function run()
{
$this->hasRun = true;
if (Log::$a) {
__log('AeArbitraryNotesCollectionView "' . $this->name . '" run {');
}
if (Log::$a) {
__log("Cacheable data {");
}
$this->prepareCacheableData();
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Uncacheable data {");
}
$this->notesCTree = [];
foreach ($this->cacheable["notes-records"] as $s) {
if (in_array($s["ID"], $this->filterOutIDs)) {
continue;
}
$noteView = new AeNoteView($s);
$r = $noteView->getNoteCTree();
$r["current?"] = $r["href"] == $this->currentURL;
$this->notesCTree[] = $r;
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$s["ID"]
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("}");
}
}
}
class AeDatabaseConfiguration
{
public $server;
public $host;
public $port = null;
public $user;
public $password;
public $name;
public $source;
public $backup_dir;
private $prefix = null;
private $subset = null;
public function __construct(
$source,
$backup_dir,
$server,
$user,
$password,
$name,
$prefix = null,
$subset = null
) {
$this->source = $source;
$this->backup_dir = $backup_dir;
$this->server = $server;
list($this->host, $this->port) = tm($this->server);
if ((string) $this->port === "") {
$this->port = null;
}
$this->user = $user;
$this->password = $password;
$this->name = $name;
$this->prefix = $prefix;
$this->subset = $subset;
}
public function hasPrefixSpecified()
{
return $this->prefix !== null;
}
public function getPrefix()
{
if ($this->prefix === null) {
throw new LogicException(
"Assertion failed: database configuration has no prefix"
);
}
return $this->prefix;
}
public function setPrefix($prefix)
{
$this->prefix = $prefix;
}
public function hasSubsetSpecified()
{
return $this->subset !== null;
}
public function setSubset($subset)
{
$this->subset = $subset;
}
public function getSubset()
{
if ($this->subset === null) {
throw new LogicException(
"Assertion failed: database configuration has no subset"
);
}
return $this->subset;
}
public function getDatabaseParamsArray()
{
return [
"server" => $this->server,
"user_name" => $this->user,
"passw" => $this->password,
"name" => $this->name,
];
}
public function getServerKeyString()
{
return $this->user . "@" . $this->server;
}
public function getDatabaseKeyString()
{
return $this->getServerKeyString() . "/" . $this->name;
}
public function getTablesKeyString()
{
return $this->getDatabaseKeyString() . "/" . $this->getPrefix() . "...";
}
public function __toString()
{
return $this->getTablesKeyString() . "?" . $this->getSubset();
}
}
class AeEnv
{
private static $t = false;
public static $j = "";
public static $h = "http";
public static $g = "";
public static $server = "";
public static $w = "";
public static $u = "";
public static $i = "http";
public static $o = "";
public static $p = "";
private static function updateBaseURL()
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
self::$o = self::$i . "://" . self::$server . self::$w . "/";
self::$p = self::$o;
if (self::$u !== (string) "") {
self::$p .= self::$u . "/";
}
}
public static function examine($cv)
{
list(self::$server) = explode(":", $cv["HTTP_HOST"]);
self::$w = substr(
$cv["PHP_SELF"],
0,
strpos($cv["PHP_SELF"], "/index.php")
);
self::$i =
(!empty($cv["HTTPS"]) && $cv["HTTPS"] !== "off" or
$cv["SERVER_PORT"] == 443 or
isset($cv["HTTP_X_FORWARDED_PROTO"]) &&
$cv["HTTP_X_FORWARDED_PROTO"] == "https" or
isset($cv["HTTP_X_HTTPS"]) && $cv["HTTP_X_HTTPS"])
? "https"
: "http";
if (getenv("E2_USER_SUBPATH")) {
self::$u = getenv("E2_USER_SUBPATH");
} elseif (getenv("REDIRECT_E2_USER_SUBPATH")) {
self::$u = getenv("REDIRECT_E2_USER_SUBPATH");
}
self::$t = true;
self::updateBaseURL();
self::$j = self::$server;
self::$h = self::$i;
self::$g = self::$o;
}
public static function setPrefersHTTPS($vv)
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
if ((bool) $vv) {
self::$i = "https";
self::updateBaseURL();
}
}
public static function setPreferredServer($bv)
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
if ($bv !== null and $_SERVER["HTTP_HOST"] !== $bv) {
self::$server = $bv;
self::updateBaseURL();
}
}
public static function showDie()
{
if (!self::$t) {
throw new LogicException("AeEnv not initialized");
}
echo "<pre>";
echo '<b>server</b>: "' . self::$server . '"<br />';
echo '<b>server_used</b>: "' . self::$j . '"<br />';
echo '<b>folder</b>: "' . self::$w . '"<br />';
echo '<b>user_subpath</b>: "' . self::$u . '"<br />';
echo '<b>protocol_used</b>: "' . self::$h . '"<br />';
echo '<b>protocol</b>: "' . self::$i . '"<br />';
echo '<b>base_url_used</b>: "' . self::$g . '"<br />';
echo '<b>base_url</b>: "' . self::$o . '"<br />';
echo "</pre>";
die();
}
}
class AeFileManager
{
private static $yv = null;
private static $nv = null;
private static $mv = null;
private static $fv = ["."];
private static $dv = ["", LOGS_DIRNAME, BACKUP_DIRNAME];
private static $sv = ["", CACHES_DIRNAME, BACKUP_DIRNAME];
private static $av = [
PICTURES_DIRNAME,
THUMBNAILS_DIRNAME,
PICTURES_DIRNAME . "remote/",
THUMBNAILS_DIRNAME . "remote/",
VIDEO_DIRNAME,
AUDIO_DIRNAME,
AVATARS_DIRNAME,
USERPIC_DIRNAME,
];
private static $qv = ["updating.psa"];
private static $lv = [
"password-hash.psa",
"password-wait.psa",
"last-comment.psa",
"new-uploads.psa",
"settings.json",
"bsi.psa",
"auth.psa",
"scheduled.psa",
"license.psa",
"checklist.psa",
];
private static function ready()
{
return self::$yv !== null and self::$nv !== null and self::$mv !== null;
}
public static function writtenDirectories($nv = null, $mv = null)
{
if (!self::ready()) {
return [];
}
if ($nv === null) {
$nv = self::$nv;
}
if ($mv === null) {
$mv = self::$mv;
}
$zv = self::$fv;
foreach (self::$dv as $kv) {
$zv[] = self::$yv . $kv;
}
foreach (self::$sv as $kv) {
$zv[] = $nv . $kv;
}
foreach (self::$av as $kv) {
$zv[] = $mv . $kv;
}
$zv = array_unique($zv);
return $zv;
}
public static function writtenFiles($nv = null, $mv = null)
{
if (!self::ready()) {
return [];
}
if ($nv === null) {
$nv = self::$nv;
}
if ($mv === null) {
$mv = self::$mv;
}
$xv = [];
foreach (self::$qv as $ev) {
$xv[] = self::$yv . $ev;
}
foreach (self::$lv as $ev) {
$xv[] = $nv . $ev;
}
$xv = array_unique($xv);
return $xv;
}
public static function setInstancePath($yv)
{
self::$yv = $yv;
}
public static function setUserPath($nv)
{
self::$nv = $nv;
}
public static function setMediaPath($mv)
{
self::$mv = $mv;
}
public static function forceAllDirectories()
{
if (!self::ready()) {
return false;
}
foreach (self::writtenDirectories() as $rv) {
@nq($rv);
}
}
public static function forceInstanceDirectories()
{
if (!self::ready()) {
return false;
}
foreach (self::$dv as $kv) {
@nq(self::$yv . $kv);
}
}
public static function forceUserDirectories($nv = null)
{
if (!self::ready()) {
return false;
}
if ($nv === null) {
$nv = self::$nv;
}
foreach (self::$sv as $kv) {
@nq($nv . $kv);
}
}
public static function forceMediaDirectories($mv = null)
{
if (!self::ready()) {
return false;
}
if ($mv === null) {
$mv = self::$mv;
}
foreach (self::$av as $kv) {
@nq($mv . $kv);
}
}
public static function getPathsWithNoWritePermissions(
$nv = null,
$mv = null
) {
if (!self::ready()) {
return [];
}
if ($nv === null) {
$nv = self::$nv;
}
if ($mv === null) {
$mv = self::$mv;
}
clearstatcache();
$tv = [];
foreach (self::writtenDirectories($nv, $mv) as $jv) {
if (is_dir($jv) and !is_writable($jv)) {
$tv[] = $jv;
}
}
foreach (self::writtenFiles($nv, $mv) as $jv) {
if (is_file($jv) and !is_writable($jv)) {
$tv[] = $jv;
}
}
return $tv;
}
}
class AeLayoutDiversityManager
{
private static $layoutsUseIndexes = [];
private static $layoutsUseIndex = 1;
private static $layoutsUseMaxIndex = 1;
public static function addLayoutsUsed($hv)
{
self::$layoutsUseIndexes[$hv] = self::$layoutsUseIndex;
self::$layoutsUseIndex++;
self::$layoutsUseMaxIndex++;
}
public static function hasLayoutBeenUsed($hv)
{
if (isset(self::$layoutsUseIndexes[$hv])) {
return true;
}
}
public static function getLayoutsUseRecency($hv)
{
if (isset(self::$layoutsUseIndexes[$hv])) {
return self::$layoutsUseIndexes[$hv] - self::$layoutsUseMaxIndex;
}
}
}
class AeMainMenuManager
{
private static $currentTags = [];
private static $parentTags = [];
static $isFavouritesCurrent = false;
static $isFavouritesParent = false;
static $isMostCommentedCurrent = false;
static $isMostCommentedParent = false;
static $isPopularCurrent = false;
static $isPopularParent = false;
static $isTagsCurrent = false;
static $isTagsParent = false;
static $isCalendarCurrent = false;
static $isCalendarParent = false;
public static function addCurrentTag($gv)
{
self::$currentTags[] = $gv;
}
public static function addParentTag($gv)
{
self::$parentTags[] = $gv;
}
public static function isCurrentTag($gv)
{
if (!empty(self::$currentTags)) {
return in_array($gv, self::$currentTags);
}
return false;
}
public static function isParentTag($gv)
{
if (!empty(self::$parentTags)) {
return in_array($gv, self::$parentTags);
}
return false;
}
}
class AeModel
{
private static $wv = [
"key" => "INT UNSIGNED AUTO_INCREMENT PRIMARY KEY",
"pkey" => "INT UNSIGNED DEFAULT '0' NOT NULL",
"pkey1" => "INT UNSIGNED DEFAULT '1' NOT NULL",
"int" => "INT DEFAULT '0' NOT NULL",
"uint" => "INT UNSIGNED DEFAULT '0' NOT NULL",
"time" => "INT UNSIGNED DEFAULT '0' NOT NULL",
"0" => "TINYINT(1) DEFAULT '0' NOT NULL",
"1" => "TINYINT(1) DEFAULT '1' NOT NULL",
"v1" => "VARCHAR(1) DEFAULT '' NOT NULL",
"v8" => "VARCHAR(8) DEFAULT '' NOT NULL",
"v15" => "VARCHAR(15) DEFAULT '' NOT NULL",
"v32" => "VARCHAR(32) DEFAULT '' NOT NULL",
"v39" => "VARCHAR(39) DEFAULT '' NOT NULL",
"v64" => "VARCHAR(64) DEFAULT '' NOT NULL",
"fid" => "VARCHAR(32) DEFAULT '" . DEFAULT_FORMATTER . "' NOT NULL",
"v255" => "VARCHAR(255) DEFAULT '' NOT NULL",
"text" => "MEDIUMTEXT",
];
private static $uv = [
"Actions" => [
["ID", "key"],
["SubsetID", "pkey1"],
["EntityID", "pkey"],
["Stamp", "time"],
["ReadCount", "int"],
],
"Aliases" => [
["ID", "key"],
["SubsetID", "pkey1"],
["EntityType", "v1"],
["EntityID", "pkey"],
["Alias", "v64"],
["Stamp", "time"],
],
"Comments" => [
["ID", "key"],
["SubsetID", "pkey1"],
["NoteID", "pkey"],
["AuthorName", "v255"],
["AuthorEmail", "v255"],
["Text", "text"],
["Reply", "text"],
["IsVisible", "1"],
["IsFavourite", "0"],
["IsReplyVisible", "0"],
["IsReplyFavourite", "0"],
["IsAnswerAware", "1"],
["IsSubscriber", "0"],
["IsSpamSuspect", "0"],
["IsNew", "0"],
["Stamp", "time"],
["LastModified", "time"],
["ReplyStamp", "time"],
["ReplyLastModified", "time"],
["IP", "v39"],
["IsGIPUsed", "0"],
["GIP", "v15"],
["GIPAuthorID", "v64"],
],
"GIPsSessions" => [
["ID", "key"],
["SubsetID", "pkey1"],
["GIP", "v15"],
["GIPAuthorID", "v64"],
["AuthorName", "v255"],
["AuthorEmail", "v255"],
["AuthorProfileLink", "v255"],
["SessionToken", "v255"],
["Stamp", "time"],
],
"Keywords" => [
["ID", "key"],
["SubsetID", "pkey1"],
["Keyword", "v255"],
["OriginalAlias", "v64"],
["PageTitle", "v255"],
["Description", "text"],
["Summary", "text"],
["Uploads", "text"],
["IsVisible", "1"],
["IsFavourite", "0"],
],
"Notes" => [
["ID", "key"],
["SubsetID", "pkey1"],
["Title", "v255"],
["Text", "text"],
["Summary", "text"],
["FormatterID", "fid"],
["OriginalAlias", "v64"],
["Uploads", "text"],
["IsPublished", "0"],
["IsCommentable", "0"],
["IsVisible", "1"],
["IsFavourite", "0"],
["Stamp", "time"],
["LastModified", "time"],
["Offset", "int"],
["IsDST", "0"],
["IsIndexed", "0"],
["IsExternal", "0"],
["ReadCount", "uint"],
["SourceID", "pkey"],
["SourceNoteID", "pkey"],
["SourceNoteURL", "v255"],
["SourceNoteJSONURL", "v255"],
["SourceNoteData", "text"],
],
"NotesKeywords" => [
["ID", "key"],
["SubsetID", "pkey1"],
["NoteID", "pkey"],
["KeywordID", "pkey"],
],
"Sources" => [
["ID", "key"],
["SubsetID", "pkey1"],
["TrueID", "pkey"],
["Title", "v255"],
["AuthorName", "v255"],
["URL", "v255"],
["PictureURL", "v255"],
["IsWhiteListed", "0"],
["IsTrusted", "0"],
],
];
private static $iv = [
"Actions" => [
["unique", ["EntityID", "Stamp"]],
["index", ["SubsetID"]],
],
"Aliases" => [
["index", ["SubsetID"]],
["index", ["Alias"]],
["index", ["EntityID"]],
],
"Comments" => [["index", ["SubsetID"]], ["index", ["NoteID"]]],
"GIPsSessions" => [
["unique", ["SubsetID", "GIP", "GIPAuthorID"]],
["index", ["SubsetID"]],
],
"Keywords" => [["index", ["SubsetID"]]],
"Notes" => [
["fulltext", ["Title", "Text"]],
["index", ["SubsetID"]],
["index", ["Stamp"]],
["index", ["SourceID"]],
["index", ["SourceNoteID"]],
],
"NotesKeywords" => [["index", ["SubsetID"]], ["index", ["NoteID"]]],
"Sources" => [["index", ["SubsetID"]]],
];
private static $ov = [
"index" => "INDEX",
"unique" => "UNIQUE INDEX",
"fulltext" => "FULLTEXT",
];
private static $pv = [
"index" => "KEY",
"unique" => "UNIQUE KEY",
"fulltext" => "FULLTEXT KEY",
];
public static function unprefixedCoreTablesNames()
{
return array_keys(self::$uv);
}
public static function unprefixedEssentialTablesNames()
{
return ["Comments", "Keywords", "Notes", "NotesKeywords"];
}
public static function assertUnprefixedTableName($cb)
{
if (!array_key_exists($cb, self::$uv)) {
throw new LogicException(
'Table "' . $cb . '" is not part of the model'
);
}
}
public static function columnsByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
return self::$uv[$cb];
}
public static function indexesByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
return self::$iv[$cb];
}
public static function softFieldsByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
$vb = [];
foreach (self::$uv[$cb] as $x) {
if (!in_array($x[1], ["key"])) {
$vb[] = $x[0];
}
}
return $vb;
}
public static function columnsAndIndexesSQLByUnprefixedTableName($cb)
{
self::assertUnprefixedTableName($cb);
$bb = [];
foreach (self::columnsByUnprefixedTableName($cb) as $yb) {
list($name, $nb) = $yb;
$bb[] = "`" . $name . "` " . self::expandColumnDefinition($nb);
}
foreach (self::indexesByUnprefixedTableName($cb) as $mb) {
list($type, $fb) = $mb;
$db = implode("", $fb);
$sb =
self::indexCreateSQLByIndexType($type) .
" `" .
$db .
"` (`" .
implode("`, `", $fb) .
"`)";
$bb[] = $sb;
}
return "(" . implode(", ", $bb) . ")";
}
public static function expandColumnDefinition($ab)
{
return self::$wv[$ab];
}
public static function indexCheckSQLByIndexType($qb)
{
return self::$pv[$qb];
}
public static function indexCreateSQLByIndexType($qb)
{
return self::$ov[$qb];
}
}
class AeNoteReadCountsProvider
{
private static $dataByNoteID = [];
private static $hasRun = false;
private static $sql = null;
public static function setSQLRequestTemplateToMapIDsToReadCounts($sql)
{
self::$sql = $sql;
}
public static function requestDeferredReadCountForNoteID($noteID)
{
self::$dataByNoteID[$noteID] = false;
}
public static function getReadCountForNoteID($noteID)
{
if (self::$sql === null) {
return false;
}
if (!self::$hasRun) {
self::run();
}
if (empty(self::$dataByNoteID[$noteID])) {
return false;
}
return self::$dataByNoteID[$noteID];
}
private static function run()
{
self::$hasRun = true;
$lb = [];
foreach (self::$dataByNoteID as $note_id => $zb) {
$lb[] = "(`ID` = " . $note_id . ")";
}
if (!count($lb)) {
return;
}
$lb = implode(" OR ", $lb);
try {
sm(
self::$sql . " AND (" . $lb . ")",
"get all requested read counts for notes"
);
$kb = qm();
foreach ($kb as $xb) {
self::$dataByNoteID[$xb["ID"]] = $xb["ReadCount"];
}
} catch (AeMySQLException $e) {
v3($e);
if (Log::$a) {
__log("Could not get requested read counts for notes");
}
}
}
}
class AeNoteView
{
private $noteRecord = [];
private $isCached = false;
private $hasRun = false;
private $cacheFilename = null;
private $noteCTree = null;
private $highlightedTags = null;
private $cacheable = [];
private $OGImages = [];
private $wantRichText = false;
private $wantCommentsLink = false;
private $wantNewCommentsCount = false;
private $wantReadHref = false;
private $wantPreviewHref = false;
private $wantControls = false;
private $wantHiddenTags = false;
private $wantSharingButtons = false;
private $wantRelatedNotes = false;
private $filterOutRelatedNoteIDs = [];
private $useLocalHref = false;
public function __construct($noteRecord)
{
$this->noteRecord = $noteRecord;
if (CACHE_NOTES) {
$this->isCached = true;
$this->cacheFilename = e2_note_cache_filename_with_id_(
$noteRecord["ID"]
);
}
}
public function setHighlightedTags($highlightedTags)
{
$this->highlightedTags = $highlightedTags;
}
public function setWantRichText($wantRichText)
{
$this->wantRichText = $wantRichText;
}
public function setWantCommentsLink($wantCommentsLink)
{
$this->wantCommentsLink = $wantCommentsLink;
}
public function setWantNewCommentsCount($wantNewCommentsCount)
{
$this->wantNewCommentsCount = $wantNewCommentsCount;
}
public function setWantReadHref($wantReadHref)
{
$this->wantReadHref = $wantReadHref;
}
public function setWantPreviewHref($wantPreviewHref)
{
$this->wantPreviewHref = $wantPreviewHref;
}
public function setWantControls($wantControls)
{
$this->wantControls = $wantControls;
}
public function setWantHiddenTags($wantHiddenTags)
{
$this->wantHiddenTags = $wantHiddenTags;
}
public function setWantSharingButtons($wantSharingButtons)
{
$this->wantSharingButtons = $wantSharingButtons;
}
public function setWantRelatedNotes($wantRelatedNotes)
{
$this->wantRelatedNotes = $wantRelatedNotes;
}
public function setFilterOutRelatedNoteIDs($filterOutRelatedNoteIDs)
{
$this->filterOutRelatedNoteIDs = $filterOutRelatedNoteIDs;
}
public function setUseLocalHref($useLocalHref)
{
$this->useLocalHref = $useLocalHref;
}
public function getNoteCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->noteCTree;
}
private function prepareCacheableData()
{
$f = [
"title" => function () {
return ay(
htmlspecialchars(
$this->noteRecord["Title"],
ENT_NOQUOTES,
"UTF-8"
)
);
},
"text-format-info" => function () {
return ly(
$this->noteRecord["FormatterID"],
$this->noteRecord["Text"],
"full"
);
},
"summary" => function () {
if ((string) $this->noteRecord["Summary"] !== "") {
return ay(
htmlspecialchars(
$this->noteRecord["Summary"],
ENT_NOQUOTES,
"UTF-8"
)
);
} else {
$eb = $this->cacheable["text-format-info"]["text-flow"];
$rb = "";
foreach ($eb as $tb) {
if (is_string($tb)) {
$rb = $tb;
break;
}
}
$rb = ly($this->noteRecord["FormatterID"], $rb, "full");
return mf($rb["text-final"]);
}
},
"comments-count" => function () {
if (!$this->noteRecord["IsPublished"]) {
return false;
} else {
return ab($this->noteRecord["ID"]);
}
},
"tags-data" => function () {
$jb = ba($this->noteRecord["ID"]);
$hb["ctree"] = [];
$hb["all-resnames-uploads"] = [];
foreach ($jb as $gb => $wb) {
$hb["ctree"][] = [
"visible?" => (bool) $wb["IsVisible"],
"name" => htmlspecialchars(
$wb["Keyword"],
ENT_NOQUOTES,
"UTF-8"
),
"href" => eq("e2m_tag", ["*tag" => $wb]),
];
$hb["all-resnames-uploads"] = array_merge(
$hb["all-resnames-uploads"],
g3("tag", $wb["ID"])
);
}
$hb["all-resnames-uploads"] = array_unique(
$hb["all-resnames-uploads"]
);
return $hb;
},
];
if ($this->isCached and is_file($this->cacheFilename)) {
($this->cacheable = @unserialize(
file_get_contents($this->cacheFilename)
)) or ($this->cacheable = []);
}
$k = false;
foreach ($f as $x => $e_) {
if (!array_key_exists($x, $this->cacheable)) {
if (Log::$a) {
__log('Build cache: "' . $x . '"');
}
$this->cacheable[$x] = $e_();
$k = true;
} else {
if (Log::$a) {
__log('Retrieved from cache: "' . $x . '"');
}
}
}
if ($this->isCached and $k) {
e3($this->cacheFilename, serialize($this->cacheable));
}
}
private function run()
{
$this->hasRun = true;
if (Log::$a) {
__log("AeNoteView run {");
}
if (Log::$a) {
__log("Cacheable data {");
}
$this->prepareCacheableData();
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Uncacheable data {");
}
$ub = false;
if ($this->noteRecord["IsPublished"]) {
if ((string) $this->noteRecord["OriginalAlias"] !== "") {
$ub = eq("e2m_note", [
"alias" => $this->noteRecord["OriginalAlias"],
]);
} else {
$ib = $this->noteRecord;
$ib["__force_ymdn"] = true;
$ub = eq("e2m_note", ["*note" => $ib]);
}
}
$ob = ia($this->noteRecord);
$pb = [(int) $this->noteRecord["LastModified"], $ob];
$l = $this->noteRecord["IsPublished"]
? [(int) $this->noteRecord["Stamp"], $ob]
: $pb;
$c3 = ff($this->noteRecord);
$v3 = @$this->cacheable["text-format-info"]["meta"][
"resources-detected"
];
if (!is_array($v3)) {
$v3 = [];
}
if (count($v3)) {
w2($v3);
}
$b3 = z2($v3);
($y3 = @unserialize($this->noteRecord["Uploads"])) or ($y3 = []);
$n3 = array_merge(
k2($v3, $y3),
$this->cacheable["tags-data"]["all-resnames-uploads"]
);
$m3 = t3($n3);
$f3 = z2($n3);
$d3 = $this->noteRecord["SourceNoteData"];
$d3 = @json_decode($d3, true);
($s3 = @$d3["og_images"][0]) or ($s3 = "");
if ($this->noteRecord["IsExternal"]) {
$a3 = bn($this->noteRecord);
} else {
$a3 = [];
}
$q3 = false;
$z3 = $this->cacheable["tags-data"]["ctree"];
foreach ($z3 as $k3 => $x3) {
if ($this->highlightedTags !== null) {
$z3[$k3]["current?"] = in_array(
$z3[$k3]["name"],
$this->highlightedTags
);
}
if (!$this->wantHiddenTags and !$z3[$k3]["visible?"]) {
unset($z3[$k3]);
}
}
if ($this->wantSharingButtons and $c3 === "public") {
$e3 = os($m3);
} else {
$e3 = false;
}
if ($this->wantNewCommentsCount) {
$r3 = sb($this->noteRecord["ID"]);
} else {
$r3 = false;
}
$this->noteCTree = [
"id" => (int) $this->noteRecord["ID"],
"title" => (string) $this->cacheable["title"],
"href" => eq("e2m_note", ["*note" => $this->noteRecord]),
"href-original" => $ub,
"time" => $l,
"last-modified" => $pb,
"text" =>
(string) $this->cacheable["text-format-info"]["text-final"],
"format-info" => $this->cacheable["text-format-info"]["meta"],
"summary" => (string) $this->cacheable["summary"],
"snippet-text" => (string) $this->cacheable["summary"],
"draft?" => $c3 === "draft",
"scheduled?" => $c3 === "scheduled",
"public?" => $c3 === "public",
"hidden?" => $c3 === "hidden",
"current?" => false,
"favourite?" =>
(bool) ($this->noteRecord["IsFavourite"] and $c3 !== "draft"),
"images" => x2($b3),
"thumbs" => e2_($b3),
"source-main-image-url" => (string) $s3,
"og-images" => $m3,
"og-images-thumbs" => e2_($f3),
"tags" => $z3,
"sharing-buttons" => $e3,
"related" => $q3,
"read-href" =>
($this->wantReadHref and $this->noteRecord["IsPublished"])
? eq("e2m_note_read", ["*note" => $this->noteRecord])
: false,
"preview-href" =>
($this->wantPreviewHref and $c3 !== "public")
? eq("e2m_note", [
"*note" => $this->noteRecord,
"preview-key" => af($this->noteRecord),
])
: false,
"comments-count" => $this->cacheable["comments-count"],
"comments-count-text" => is_int($this->cacheable["comments-count"])
? e2l_get_string("gs--n-comments", [
"number" => $this->cacheable["comments-count"],
])
: "",
"new-comments-count" => $r3,
"new-comments-count-text" => is_int($r3)
? e2l_get_string("gs--comments-n-new", ["number" => $r3])
: "",
"comments-link?" =>
(bool) ($this->wantCommentsLink and
$this->noteRecord["IsPublished"] and
(xb($this->noteRecord) or
$this->cacheable["comments-count"] > 0)),
];
if ($this->noteRecord["IsExternal"]) {
$this->noteCTree = array_merge($this->noteCTree, $a3);
$this->noteCTree["href-original"] =
$this->noteCTree["href-external"];
if (!$this->useLocalHref) {
$this->noteCTree["href"] = $this->noteCTree["href-external"];
}
}
if ($this->wantControls) {
$this->noteCTree["edit-href"] = eq("e2m_note_edit", [
"*note" => $this->noteRecord,
]);
if (
$this->noteRecord["IsPublished"] and
!$this->noteRecord["IsVisible"]
) {
$this->noteCTree["show-action"] = eq("e2s_note_flag", [
"*note" => $this->noteRecord,
"flag" => "IsVisible",
"value" => 1,
]);
}
if ($this->noteRecord["IsPublished"]) {
$this->noteCTree["favourite-toggle-action"] = eq(
"e2s_note_flag_favourite",
[
"*note" => $this->noteRecord,
"value" => !$this->noteRecord["IsFavourite"],
]
);
}
}
$this->noteCTree["href-comments"] =
$this->noteCTree["href"] . "#comments";
if (Log::$a) {
__log("}");
}
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$this->noteRecord["ID"]
);
if (Log::$a) {
__log("}");
}
}
}
class AePageableNotesView
{
private $candy;
private $parameters;
private $pageExists = false;
private $isCached = false;
private $hasRun = false;
private $sql = null;
private $sql_count = null;
private $highlightedTags = null;
private $cacheFilename = null;
private $prevPageTitle = null;
private $nextPageTitle = null;
private $totalNotes = null;
private $totalPages = null;
private $notesCTree = null;
private $pagesCTree = null;
private $wantPaging = false;
private $wantNewCommentsCount = false;
private $wantReadHrefs = false;
private $wantPreviewHrefs = false;
private $wantControls = false;
private $wantHiddenTags = false;
private $wantRelatedNotes = false;
private $useLocalHrefs = false;
private $page = 1;
private $limit = 10;
public function __construct($candy, $parameters)
{
$this->candy = $candy;
$this->parameters = $parameters;
if (empty($parameters["page"])) {
$this->page = 1;
} else {
$this->page = (int) $parameters["page"];
}
}
public function setSQLCountRequest($sql_count)
{
if (strpos($sql_count, "SELECT COUNT(*) Total FROM ") !== 0) {
die(
'AePageableNotesView: Count request must start with "SELECT COUNT(*) Total FROM "'
);
}
$this->sql_count = $sql_count;
}
public function setLimitlessSQLRequest($sql)
{
if (strstr($sql, "LIMIT")) {
die('AePageableNotesView: Request must not contain "LIMIT"');
}
$this->sql = $sql;
if ($this->sql_count === null) {
if (strpos($sql, "SELECT * ") === 0) {
$this->sql_count = "SELECT COUNT(*) Total " . substr($sql, 9);
} else {
die("AePageableNotesView: setSQLCountRequest () must be used");
}
}
}
public function setPortionSize($limit)
{
$this->limit = abs((int) $limit);
}
public function setNextPrevPageTitles($nextPageTitle, $prevPageTitle)
{
$this->nextPageTitle = $nextPageTitle;
$this->prevPageTitle = $prevPageTitle;
}
public function setHighlightedTags($highlightedTags)
{
$this->highlightedTags = $highlightedTags;
}
public function setCacheFilename($cacheFilename)
{
$this->isCached = true;
$this->cacheFilename = $cacheFilename;
}
public function setWantPaging($wantPaging)
{
$this->wantPaging = $wantPaging;
}
public function setWantNewCommentsCount($wantNewCommentsCount)
{
$this->wantNewCommentsCount = $wantNewCommentsCount;
}
public function setWantReadHrefs($wantReadHrefs)
{
$this->wantReadHrefs = $wantReadHrefs;
}
public function setWantPreviewHrefs($wantPreviewHrefs)
{
$this->wantPreviewHrefs = $wantPreviewHrefs;
}
public function setWantControls($wantControls)
{
$this->wantControls = $wantControls;
}
public function setWantHiddenTags($wantHiddenTags)
{
$this->wantHiddenTags = $wantHiddenTags;
}
public function setWantRelatedNotes($wantRelatedNotes)
{
$this->wantRelatedNotes = $wantRelatedNotes;
}
public function setUseLocalHrefs($useLocalHrefs)
{
$this->useLocalHrefs = $useLocalHrefs;
}
public function isExistingPage()
{
if (!$this->hasRun) {
$this->run();
}
return $this->pageExists;
}
public function isFirstPage()
{
return $this->page === 1;
}
public function isFirstPageOfEmptyView()
{
if (!$this->hasRun) {
$this->run();
}
return $this->page === 1 and $this->totalPages === 0;
}
public function getTotalNotes()
{
if (!$this->hasRun) {
$this->run();
}
return $this->totalNotes;
}
public function getTotalPages()
{
if (!$this->hasRun) {
$this->run();
}
return $this->totalPages;
}
public function getNotesCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->notesCTree;
}
public function getPagesCTree()
{
if (!$this->hasRun) {
$this->run();
}
return $this->pagesCTree;
}
private function prepareCacheableData()
{
$this->totalNotes = 0;
if ($this->limit) {
$t3 = ($this->page - 1) * $this->limit;
$this->sql .= " LIMIT " . $t3 . ", " . $this->limit;
}
sm(
$this->sql_count,
'count total notes of "' . $this->candy . '" list'
);
$j3 = qm();
$this->totalNotes = $j3 ? (int) $j3[0]["Total"] : 0;
sm($this->sql, 'get limited full notes "' . $this->candy . '" list');
$h3 = qm();
$l3 = [];
foreach ($h3 as $k3 => $s) {
$l3[] = $s["ID"];
}
$this->notesCTree = [];
foreach ($h3 as $k3 => $s) {
$noteView = new AeNoteView($s);
$noteView->setWantNewCommentsCount($this->wantNewCommentsCount);
$noteView->setWantReadHref($this->wantReadHrefs);
$noteView->setWantPreviewHref($this->wantPreviewHrefs);
$noteView->setWantControls($this->wantControls);
$noteView->setWantHiddenTags($this->wantHiddenTags);
$noteView->setWantCommentsLink(true);
$noteView->setWantRelatedNotes($this->wantRelatedNotes);
$noteView->setFilterOutRelatedNoteIDs($l3);
$noteView->setHighlightedTags($this->highlightedTags);
$noteView->setUseLocalHref($this->useLocalHrefs);
$this->notesCTree[] = $noteView->getNoteCTree();
}
$this->pagesCTree = [];
if (
$this->limit and
($this->totalPages = (int) ceil($this->totalNotes / $this->limit))
) {
$this->pagesCTree["timeline?"] = true;
$this->pagesCTree["count"] = (int) $this->totalPages;
$this->pagesCTree["this"] = (int) $this->page;
if ($this->wantPaging) {
$this->pagesCTree["earlier-title"] = $this->nextPageTitle;
$this->pagesCTree["later-title"] = $this->prevPageTitle;
$g3 = $this->parameters;
if ($this->page < $this->totalPages) {
$g3["page"] = $this->page + 1;
$this->pagesCTree["earlier-href"] = eq($this->candy, $g3);
}
if ($this->page > 1) {
$g3["page"] = $this->page - 1;
$this->pagesCTree["later-href"] = eq($this->candy, $g3);
}
}
}
}
private function run()
{
$this->hasRun = true;
if ($this->isCached and is_file($this->cacheFilename)) {
$w3 = @unserialize(file_get_contents($this->cacheFilename));
$this->totalNotes = @$w3["notes_total"];
$this->notesCTree = @$w3["notes_ctree"];
$this->pagesCTree = @$w3["pages_ctree"];
$this->totalPages = @$this->pagesCTree["count"];
}
if (
is_int($this->totalNotes) and
is_array($this->notesCTree) and
is_array($this->pagesCTree) and
is_int($this->totalPages)
) {
if (Log::$a) {
__log("Retrieved cached CTree");
}
} else {
$this->prepareCacheableData();
if ($this->isCached) {
e3(
$this->cacheFilename,
serialize([
"notes_total" => $this->totalNotes,
"notes_ctree" => $this->notesCTree,
"pages_ctree" => $this->pagesCTree,
])
);
}
}
foreach ($this->notesCTree as $u3) {
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$u3["id"]
);
if (empty($u3["related"]["each"])) {
continue;
}
foreach ($u3["related"]["each"] as $i3) {
AeNoteReadCountsProvider::requestDeferredReadCountForNoteID(
$i3["id"]
);
}
}
$this->pageExists =
($this->totalPages > 0 and
$this->page >= 1 and
$this->page <= $this->totalPages);
}
}
class AeRequest
{
public $method = "GET";
public $url = "";
public $candy = "";
public $parameters = [];
public function __construct($cv, $o3)
{
$this->method = $cv["REQUEST_METHOD"];
$p3 = urldecode((string) @$o3["go"]);
if (substr($p3, 0, strlen(AeEnv::$u)) === AeEnv::$u) {
$p3 = substr($p3, strlen(AeEnv::$u));
}
$this->url =
AeEnv::$h . "://" . AeEnv::$j . AeEnv::$w . AeEnv::$u . "/" . $p3;
list($this->candy, $this->parameters) = rq($p3);
}
public function toBeFulfilledByService()
{
return substr($this->candy, 0, 4) == "e2s_";
}
public function requiresInstallation()
{
return !in_array($this->candy, [
"e2s_build",
"e2m_info",
"e2m_install",
"e2j_check_db_config",
"e2j_list_databases",
"e2s_instantiate",
"e2s_install",
]);
}
public function requiresVersionMatch()
{
return $this->requiresInstallation();
}
public function requiresScheduleCheckBeforeServing()
{
return $this->requiresInstallation();
}
public function shouldSlowDownAJAXResponse()
{
return in_array($this->candy, [
"e2j_check_db_config",
"e2j_list_databases",
"e2j_check_password",
"e2j_userpic_upload",
"e2j_userpic_remove",
"e2j_file_upload",
"e2j_file_rename",
"e2j_file_remove",
"e2j_note_livesave",
"e2s_note_flag_favourite",
"e2s_comment_flag_ajax",
"e2s_tag_flag_ajax",
]);
}
public function requiresSignIn()
{
return !empty($this->candy) and
is_callable($this->candy) and
$this->requiresInstallation() and
!in_array($this->candy, [
"e2m_info",
"e2m_frontpage",
"e2m_rss",
"e2m_json",
"e2m_note",
"e2m_note_json",
"e2m_note_read",
"e2m_tags",
"e2m_tag",
"e2m_untagged",
"e2m_tag_rss",
"e2m_tag_json",
"e2m_popular",
"e2m_favourites",
"e2m_most_commented",
"e2m_found",
"e2m_comments",
"e2m_everything",
"e2m_sitemap_xml",
"e2m_year",
"e2m_month",
"e2m_day",
"e2m_calendar",
"e2m_unsubscribe",
"e2m_theme_preview",
"e2m_error404",
"e2m_password_reset",
"e2s_password_reset_email",
"e2m_password",
"e2s_password_save",
"e2s_sign_in",
"e2m_sign_out",
"e2m_gip_sign_in",
"e2m_gip_sign_in_callback",
"e2m_gip_sign_out",
"e2s_comment_process",
"e2s_search",
"e2s_bsi_step",
"e2j_check_password",
"e2s_retrieve",
"e2s_notify",
"e2s_dump",
]);
}
public function allowedInReadOnlyMode()
{
return !in_array($this->candy, [
"e2m_write",
"e2m_note_edit",
"e2s_note_process",
"e2s_note_publish",
"e2s_note_delete",
"e2s_note_flag_favourite",
"e2s_note_flag",
"e2m_comment_edit",
"e2m_comment_delete",
"e2m_comment_reply",
"e2m_comment_reply_delete",
"e2m_comment_flag",
"e2s_comment_flag_ajax",
"e2m_unsubscribe",
"e2s_comment_process",
"e2m_settings",
"e2m_timezone",
]);
}
public function replaceWith($cy)
{
$this->candy = $cy;
}
}
function c()
{
global $_config;
$vy = [
"new-note-href" => eq("e2m_write"),
"drafts-href" => eq("e2m_drafts", ["page" => 1]),
"drafts-count" => (int) nf(false, true),
"settings-href" => eq("e2m_settings"),
"theme-preview-href" => eq("e2m_theme_preview", ["theme" => ""]),
"password-href" => eq("e2m_password", ["recovery-key" => ""]),
"database-href" => eq("e2m_database"),
"timezone-href" => eq("e2m_timezone"),
"sessions-href" => eq("e2m_sessions"),
"sign-out-href" => eq("e2m_sign_out"),
];
if (us()) {
$vy["get-backup-href"] = eq("e2m_get_backup");
}
if (@$_config["read_only"]) {
unset($vy["new-note-href"]);
unset($vy["settings-href"]);
unset($vy["timezone-href"]);
}
if (!$_config["allow_themes_preview"]) {
unset($vy["theme-preview-href"]);
}
$databaseConfiguration = bl();
if (
$databaseConfiguration->source !== "settings" or
!$_config["allow_db_config"]
) {
unset($vy["database-href"]);
}
list($r3, $by) = lb($databaseConfiguration);
if ($r3) {
$vy["new-comments-count"] = $r3;
$vy["new-comments-href"] = $by;
}
return $vy;
}
function v($yy, AeDatabaseConfiguration $databaseConfiguration, $ny)
{
static $my = null;
$fy = ($yy === USER_DIR and $databaseConfiguration == bl());
if ($ny) {
if ($yy !== false) {
@unlink($yy . CACHE_FILENAME_ALIASMAP);
}
if ($fy) {
$my = null;
}
return;
}
if ($fy and is_array($my)) {
return $my;
}
$dy = null;
if (CACHE_ALIASMAP and is_file($yy . CACHE_FILENAME_ALIASMAP)) {
$dy = @unserialize(file_get_contents($yy . CACHE_FILENAME_ALIASMAP));
}
if (is_array($dy)) {
if ($fy) {
$my = $dy;
}
return $dy;
}
if (Log::$a) {
__log("Build aliasmap {");
}
$dy = [];
am(
$databaseConfiguration,
"SELECT `EntityType`, `EntityID`, `Alias` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Aliases` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `Stamp` IN (" .
"SELECT MAX(`Stamp`) `MaxStamp` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Aliases` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"GROUP BY `EntityType`, `EntityID`" .
")",
"get all active aliases"
);
foreach (qm() as $sy) {
$ay = $sy["EntityType"] . $sy["EntityID"];
$dy[$ay] = $sy["Alias"];
}
am(
$databaseConfiguration,
"SELECT `ID`, `Stamp`, `Offset`, `IsDST`, `OriginalAlias` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `IsPublished` = 1 " .
"ORDER BY `Stamp`",
"get all notes to cache y/d/m/n urls"
);
$qy = 0;
$ly = false;
foreach (qm() as $zy) {
$ay = "n" . $zy["ID"];
$ky = y1("Y/m/d", $zy["Stamp"], ia($zy));
if ($ky !== $ly) {
$qy = 0;
}
$qy++;
$xy = $ky . "/" . $qy;
if (empty($dy[$ay])) {
$dy[$ay] = $xy;
} else {
if ((string) $zy["OriginalAlias"] === "") {
$dy[$ay . "-ymdn"] = $xy;
}
}
$ly = $ky;
}
am(
$databaseConfiguration,
"SELECT `ID`, `OriginalAlias` " .
"FROM `" .
$databaseConfiguration->getPrefix() .
"Keywords` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset(),
"get original active aliases for tags"
);
foreach (qm() as $wb) {
$ay = "t" . $wb["ID"];
if (empty($dy[$ay])) {
$dy[$ay] = $wb["OriginalAlias"];
}
}
if (CACHE_ALIASMAP) {
e3($yy . CACHE_FILENAME_ALIASMAP, serialize($dy));
}
if ($fy) {
$my = $dy;
}
if (Log::$a) {
__log("}");
}
return $dy;
}
function b($ny = false)
{
return v(USER_DIR, bl(), $ny);
}
function e2_alias_of_note_with_id_($ey)
{
$ry = b()["n" . $ey];
if (
preg_match(
'/^(?P<year>\d{4})\/(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<day_number>\d+)$/s',
$ry
)
) {
$ry = "";
}
return $ry;
}
function e2ali__alias_from_title_($source)
{
global $_config;
$ty = $source;
if (array_key_exists("autoreplace_for_aliases", $_config)) {
$ty = strtr($ty, $_config["autoreplace_for_aliases"]);
}
$ty = t1($ty);
$ty = str_replace('\'', "", $ty);
$ty = str_replace("", "", $ty);
$ty = str_replace(chr(146), "", $ty);
$jy = "";
for ($gb = 0; $gb < strlen($ty); ++$gb) {
if (
ord($ty[$gb]) >= 48 and ord($ty[$gb]) <= 57 or
ord($ty[$gb]) >= 65 and ord($ty[$gb]) <= 90 or
ord($ty[$gb]) >= 97 and ord($ty[$gb]) <= 122 or
0
) {
$jy .= $ty[$gb];
} else {
$jy .= "-";
}
}
$jy = preg_replace("/\-+/", "-", $jy);
$jy = trim($jy, "-");
$jy = strtolower($jy);
if ($jy == "-") {
$jy = "";
}
$jy = substr($jy, 0, ALIAS_MAX_LENGTH);
return $jy;
}
function m(AeDatabaseConfiguration $databaseConfiguration, $ry)
{
if ((string) $ry === "") {
return false;
}
am(
$databaseConfiguration,
"SELECT * FROM `" .
$databaseConfiguration->getPrefix() .
"Aliases` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `Alias` = '" .
$ry .
"' " .
"ORDER BY `Stamp` LIMIT 1",
'get alias record for alias "' . $ry . '"'
);
$h3 = qm();
if (count($h3) == 1) {
return $h3[0];
} else {
return false;
}
}
function f($ry)
{
if ((string) $ry === "") {
return false;
}
if (Log::$a) {
__log('Get entity type and id from alias "' . $ry . '"');
}
$hy = @array_flip(b());
$ay = (string) @$hy[$ry];
if (strlen($ay) > 0 and ($ay[0] == "n" or $ay[0] == "t")) {
$xb = ["type" => $ay[0], "id" => (int) substr($ay, 1)];
return $xb;
}
$sy = m(bl(), $ry);
if (!$sy) {
return false;
}
$xb = ["type" => $sy["EntityType"], "id" => (int) $sy["EntityID"]];
if (Log::$a) {
__log(
'Got entity type "' . $xb["type"] . '" and id "' . $xb["id"] . '"'
);
}
return $xb;
}
function d(
$yy,
AeDatabaseConfiguration $databaseConfiguration,
$iy,
$uy,
$gy,
$source,
$wy = 1
) {
if (Log::$a) {
__log(
'Aliases: "' .
$iy .
'" available alias for source "' .
$source .
'"'
);
}
$oy = $uy . $gy;
if ($iy === "set" and $oy === "") {
return false;
}
$jy = e2ali__alias_from_title_($source);
if ($source !== "" and $jy === "") {
$jy = (string) $wy;
} elseif ($wy > 1) {
$py = "-" . $wy;
$jy = substr($jy, 0, ALIAS_MAX_LENGTH - strlen($py)) . $py;
}
$dy = v($yy, $databaseConfiguration, false);
if ($sy = m($databaseConfiguration, $jy)) {
$cn = $sy["EntityType"] . $sy["EntityID"];
if ($oy === $cn or $jy !== $dy[$cn]) {
if ($iy == "find") {
return $jy;
}
if ($iy == "set") {
if (Log::$a) {
__log("Aliases: update alias timestamp");
}
fm($databaseConfiguration, "Aliases", [
"ID" => $sy["ID"],
"EntityType" => $uy,
"EntityID" => $gy,
"Alias" => $jy,
"Stamp" => time(),
]);
v($yy, $databaseConfiguration, true);
return $jy;
}
} else {
return d(
$yy,
$databaseConfiguration,
$iy,
$uy,
$gy,
$source,
$wy + 1
);
}
} else {
if ($oy !== "" and $jy == "") {
if (
preg_match(
"/(?P<year>\d{4})\/(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<day_number>\d+)/",
$dy[$oy]
)
) {
if (Log::$a) {
__log("Aliases: d/m/y/n was already used for this entity");
}
return "";
}
}
if (Log::$a) {
__log(
"Aliases: its an empty alias, and it was not being used for this entity"
);
}
if ($uy == "t" and ($vn = qa($databaseConfiguration, $jy))) {
if ($vn["ID"] != $gy) {
return d(
$yy,
$databaseConfiguration,
$iy,
$uy,
$gy,
$source,
$wy + 1
);
}
}
if ($iy == "find") {
return $jy;
}
if ($iy == "set") {
mm($databaseConfiguration, "Aliases", [
"EntityType" => $uy,
"EntityID" => $gy,
"Alias" => $jy,
"Stamp" => time(),
]);
v($yy, $databaseConfiguration, true);
return $jy;
}
}
return "";
}
function e2_delete_aliases_for_entity_($type, $ey)
{
global $_config;
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Aliases` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `EntityType` = '" .
$type .
"' " .
"AND `EntityID`=" .
((int) $ey),
"delete aliases of note"
);
}
function a()
{
static $bn;
$yn = ls();
if (empty($bn)) {
$bn = md5(AeEnv::$p . "email" . $yn);
}
return $bn;
}
function q()
{
static $nn;
$yn = ls();
if (empty($nn)) {
$nn = md5(AeEnv::$p . "nospam" . $yn . date("n-Y"));
}
return $nn;
}
function l()
{
static $mn;
$yn = ls();
if (empty($mn)) {
$mn = md5(
AeEnv::$p . "nospam" . $yn . date("n-Y", strtotime("-1 month"))
);
}
return $mn;
}
function z($note_id)
{
$yn = ls();
return x1("comment_" . md5(AeEnv::$p . "nospam_cookie" . $yn . $note_id));
}
function k()
{
$fn_ = $_SERVER["HTTP_USER_AGENT"];
$yn = ls();
return md5(AeEnv::$p . "nospam_cookie" . $yn . $fn_);
}
function x()
{
if (array_key_exists("email", $_POST) and $_POST["email"] !== "") {
return true;
}
$nn = q();
$mn = l();
if (!array_key_exists($nn, $_POST) and !array_key_exists($mn, $_POST)) {
return true;
}
if (
array_key_exists($nn, $_POST) and $_POST[$nn] !== "" or
array_key_exists($mn, $_POST) and $_POST[$mn] !== ""
) {
return true;
}
if (!array_key_exists("comment", $_POST) or strlen($_POST["comment"]) > 6) {
return true;
}
return false;
}
function e2_cookie_data_is_spam_suspicios_for_note_id_($note_id)
{
if (
!array_key_exists(z($note_id), $_COOKIE) or
$_COOKIE[z($note_id)] !== k()
) {
return true;
}
return false;
}
function e2m_year($parameters = [])
{
global $_strings, $_config;
$dn = $parameters["year"];
$sn = e2l_get_string("pt--nth-year", ["year" => $dn]);
if (!j($dn)) {
return e2m_error404();
}
AeMainMenuManager::$isCalendarCurrent = false;
AeMainMenuManager::$isCalendarParent = true;
$an = gmmktime(0, 0, 0, 1, 1, $dn - 1);
$qn = gmmktime(0, 0, 0, 1, 1, $dn + 1);
list($ln, $zn) = e2__fruitful_neighbours_with_ymd_($dn);
$kn = "e2m_year";
if ($ln) {
$xn["prev-href"] = eq($kn, e2__parameters_with_timestamp_($ln));
$xn["prev-jump?"] = (bool) (gmdate("Y", $an) != gmdate("Y", $ln));
$xn["prev-title"] = gmdate("Y", $ln);
}
if ($zn) {
$xn["next-href"] = eq($kn, e2__parameters_with_timestamp_($zn));
$xn["next-jump?"] = (bool) (gmdate("Y", $qn) != gmdate("Y", $zn));
$xn["next-title"] = gmdate("Y", $zn);
}
$xn["timeline?"] = false;
$xn["this"] = $dn;
$xn["this-title"] = $dn;
list($en, $rn) = s1($dn);
$vb = [
"title" => $sn,
"heading" => $sn,
"pages" => $xn,
"year" => (int) $dn,
"calendar" => t($dn, false, false),
];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df(ys()) .
"AND `Stamp` BETWEEN " .
$en .
" " .
"AND " .
$rn .
" " .
"ORDER BY `Stamp`",
"get all notes for the year"
);
$h3 = qm();
$tn = w(true, $h3, $dn);
if (count($tn)) {
$vb["notes-list"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
return $vb;
}
function e2m_month($parameters = [])
{
global $_strings, $_config;
$dn = $parameters["year"];
$jn = $parameters["month"];
$sn = e2l_get_string("pt--nth-month-of-nth-year", [
"year" => $dn,
"month" => $jn,
]);
if (!j($dn, $jn)) {
return e2m_error404();
}
AeMainMenuManager::$isCalendarCurrent = false;
AeMainMenuManager::$isCalendarParent = true;
$an = gmmktime(0, 0, 0, $jn - 1, 1, (int) $dn);
$qn = gmmktime(0, 0, 0, $jn + 1, 1, (int) $dn);
list($ln, $zn) = e2__fruitful_neighbours_with_ymd_($dn, $jn);
$kn = "e2m_month";
if ($ln) {
$xn["prev-href"] = eq($kn, e2__parameters_with_timestamp_($ln));
$xn["prev-jump?"] = (bool) (gmdate("Y/m", $an) != gmdate("Y/m", $ln));
$xn["prev-title"] = e2l_get_string("gs--nth-month-of-nth-year", [
"year" => gmdate("Y", $ln),
"month" => gmdate("n", $ln),
]);
}
if ($zn) {
$xn["next-href"] = eq($kn, e2__parameters_with_timestamp_($zn));
$xn["next-jump?"] = (bool) (gmdate("Y/m", $qn) != gmdate("Y/m", $zn));
$xn["next-title"] = e2l_get_string("gs--nth-month-of-nth-year", [
"year" => gmdate("Y", $zn),
"month" => gmdate("n", $zn),
]);
}
$xn["timeline?"] = false;
$xn["this-title"] = $sn;
list($en, $rn) = s1($dn, $jn);
$vb = [
"title" => $sn,
"heading" => $sn,
"calendar" => t($dn, $jn, false),
"pages" => $xn,
"year" => (int) $dn,
"month" => (int) $jn,
];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df(ys()) .
"AND `Stamp` BETWEEN " .
$en .
" " .
"AND " .
$rn .
" " .
"ORDER BY `Stamp`",
"get all notes for the month"
);
$h3 = qm();
$tn = w(true, $h3, $dn, $jn);
if (count($tn)) {
$vb["notes-list"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
return $vb;
}
function e2m_day($parameters = [])
{
global $_strings, $_config, $_current_url;
$dn = (int) $parameters["year"];
$jn = (int) $parameters["month"];
$hn = (int) $parameters["day"];
if (!j($dn, $jn, $hn)) {
return e2m_error404();
}
AeMainMenuManager::$isCalendarCurrent = false;
AeMainMenuManager::$isCalendarParent = true;
if ($_current_url === p()) {
AeMainMenuManager::$isCalendarCurrent = true;
AeMainMenuManager::$isCalendarParent = false;
}
$sn = e2l_get_string("pt--nth-day-of-nth-month-of-nth-year", [
"year" => $dn,
"month" => $jn,
"day" => $hn,
]);
$an = gmmktime(0, 0, 0, (int) $jn, $hn - 1, (int) $dn);
$qn = gmmktime(0, 0, 0, (int) $jn, $hn + 1, (int) $dn);
list($ln, $zn) = e2__fruitful_neighbours_with_ymd_($dn, $jn, $hn);
$kn = "e2m_day";
if ($ln) {
$xn["prev-href"] = eq($kn, e2__parameters_with_timestamp_($ln));
$xn["prev-jump?"] =
(bool) (gmdate("Y/m/d", $an) != gmdate("Y/m/d", $ln));
$xn["prev-title"] = e2l_get_string(
"gs--nth-day-of-nth-month-of-nth-year",
[
"year" => gmdate("Y", $ln),
"month" => gmdate("n", $ln),
"day" => gmdate("j", $ln),
]
);
}
if ($zn) {
$xn["next-href"] = eq($kn, e2__parameters_with_timestamp_($zn));
$xn["next-jump?"] =
(bool) (gmdate("Y/m/d", $qn) != gmdate("Y/m/d", $zn));
$xn["next-title"] = e2l_get_string(
"gs--nth-day-of-nth-month-of-nth-year",
[
"year" => gmdate("Y", $zn),
"month" => gmdate("n", $zn),
"day" => gmdate("j", $zn),
]
);
}
$xn["timeline?"] = false;
$xn["this-title"] = $sn;
$vb = [
"title" => $sn,
"heading" => $sn,
"pages" => $xn,
"calendar" => t($dn, $jn, $hn),
];
$h3 = om($dn, $jn, $hn);
$h3 = array_reverse($h3);
$gn = ys();
$tn = [];
foreach ($h3 as $k3 => $zy) {
if (!(ff($zy) === "public" or $gn and $zy["IsPublished"])) {
continue;
}
$noteView = new AeNoteView($zy);
$noteView->setWantNewCommentsCount($gn);
$noteView->setWantReadHref($_config["count_reads"]);
$noteView->setWantControls($gn and !@$_config["read_only"]);
$noteView->setWantHiddenTags($gn);
$noteView->setWantCommentsLink(true);
$tn[] = $noteView->getNoteCTree();
}
if (count($tn)) {
$vb["notes"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-such-notes"];
}
return $vb;
}
function e2m_calendar()
{
z1(p());
}
function r($wn)
{
global $_config;
$tn = null;
if (CACHE_FULLLIST and is_file(USER_DIR . CACHE_FILENAME_FULLLIST)) {
$tn = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_FULLLIST)
);
if (Log::$a) {
__log("Retrieving full notes list from cache...");
}
}
if (!is_array($tn)) {
if (Log::$a) {
__log("Retrieving full notes list from database...");
}
sm(
"SELECT `ID`, `Title`, `Stamp`, `LastModified`, `Offset`, `IsDST`, " .
"`IsFavourite`, `IsPublished`, `IsVisible`, `SourceNoteURL`, `OriginalAlias` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished` = 1 " .
df() .
"ORDER BY `Stamp`",
"get full notes list"
);
$h3 = qm();
$tn = w($wn, $h3);
if ($wn) {
if (CACHE_FULLLIST) {
e3(USER_DIR . CACHE_FILENAME_FULLLIST, serialize($tn));
}
}
}
return $tn;
}
function e2m_everything($parameters = [])
{
global $_strings;
$tn = r(true);
$un = count($tn);
$sn = e2l_get_string("pt--n-posts", ["number" => $un]);
$vb = ["title" => $sn, "heading" => $sn];
if (count($tn)) {
$vb["notes-list"] = $tn;
} else {
$vb["nothing"] = $_strings["gs--no-notes"];
}
return $vb;
}
function e2m_sitemap_xml($parameters = [])
{
global $_config;
$tn = r(false);
if (@$_config["dev_xml_as_text"]) {
header("Content-Type: text/plain");
} else {
header("Content-type: application/xml; charset=utf-8");
}
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' .
"\r\n";
if (count($tn)) {
$in = @$tn[0]["last-modified"];
echo "<url>" . "\r\n";
echo "<loc>" . eq("e2m_frontpage", ["page" => 1]) . "</loc>" . "\r\n";
echo "<lastmod>";
echo gmdate("Y-m-d\TH:i:s\Z", $in[0]);
echo "</lastmod>" . "\r\n";
echo "<changefreq>hourly</changefreq>";
echo "</url>" . "\r\n";
foreach ($tn as $r) {
echo "<url>" . "\r\n";
echo "<loc>";
echo $r["href"];
echo "</loc>" . "\r\n";
echo "<lastmod>";
echo gmdate("Y-m-d\TH:i:s\Z", $r["last-modified"][0]);
echo "</lastmod>" . "\r\n";
echo "</url>" . "\r\n";
}
}
echo "</urlset>" . "\r\n";
die();
}
function t($dn, $jn, $hn)
{
if (is_numeric($jn)) {
$on = y1("t", gmmktime(0, 0, 0, (int) $jn, 1, (int) $dn), oa());
} else {
$on = 0;
}
$pn = cv("start");
$cm = y1("Y", $pn["stamp"], $pn["timezone"]);
$vm = n1("Y", time());
$bm = n1("m", time());
if ((int) $dn == (int) $cm) {
$ym = y1("m", $pn["stamp"], $pn["timezone"]);
} else {
$ym = 1;
}
if ((int) $dn == (int) $vm) {
$bm = n1("m", time());
} else {
$bm = 12;
}
if ((int) $dn == (int) $cm and (int) $jn == (int) $ym) {
$nm = y1("d", $pn["stamp"], $pn["timezone"]);
} else {
$nm = 1;
}
if ((int) $dn == (int) $vm and (int) $jn == (int) $bm) {
$mm = n1("d", time());
} else {
$mm = $on;
}
if (1) {
$fm = u();
for ($gb = $cm; $gb <= $vm; ++$gb) {
$dm = gmmktime(0, 0, 0, 1, 1, (int) $gb);
$sm[$gb] = [
"number" => $gb,
"start-time" => [$dm, oa()],
"href" => eq("e2m_year", ["year" => gmdate("Y", $dm)]),
"this?" => (bool) ($gb == $dn),
"real?" => true,
"fruitful?" => @in_array(gmdate("Y", $dm), $fm),
];
}
$am["years"] = $sm;
}
if (1) {
$qm = i($dn);
for ($gb = 1; $gb <= 12; ++$gb) {
$dm = gmmktime(0, 0, 0, (int) $gb, 1, (int) $dn);
$lm[$gb] = [
"number" => $gb,
"start-time" => [$dm, oa()],
"href" => eq("e2m_month", [
"year" => gmdate("Y", $dm),
"month" => gmdate("m", $dm),
]),
"this?" => (bool) ($gb == $jn),
"real?" => $gb >= $ym and $gb <= $bm,
"fruitful?" => @in_array(gmdate("n", $dm), $qm),
];
}
$am["months"] = $lm;
}
if ($on) {
$zm = o($dn, $jn);
for ($gb = 1; $gb <= $on; ++$gb) {
$dm = gmmktime(0, 0, 0, (int) $jn, (int) $gb, (int) $dn);
$km[$gb] = [
"number" => $gb,
"start-time" => [$dm, oa()],
"href" => eq("e2m_day", [
"year" => gmdate("Y", $dm),
"month" => gmdate("m", $dm),
"day" => gmdate("d", $dm),
]),
"this?" => (bool) ($gb == $hn),
"real?" => $gb >= $nm and $gb <= $mm,
"fruitful?" => @in_array(gmdate("d", $dm), $zm),
];
}
$am["days"] = $km;
}
return $am;
}
function j($dn, $jn = false, $hn = false)
{
$pn = cv("start");
if ($pn === false) {
return false;
}
$xm = y1("Y", $pn["stamp"], $pn["timezone"]);
$em = n1("Y", time());
if ($jn === false) {
return (bool) ($dn >= $xm and $dn <= $em);
} else {
$rm = y1("n", $pn["stamp"], $pn["timezone"]);
$tm = n1("n", time());
if ($hn === false) {
return (bool) ($jn >= 1 and
$jn <= 12 and
($dn > $xm and $dn < $em or
$dn == $xm and $jn >= $rm or
$dn == $em and $jn <= $tm));
} else {
$jm = y1("j", $pn["stamp"], $pn["timezone"]);
$hm = n1("j", time());
if (1) {
return (bool) (checkdate($jn, $hn, $dn) and
($dn > $xm and $dn < $em or
$dn == $xm and $jn > $rm or
$dn == $xm and $jn == $rm and $hn >= $jm or
$dn == $em and $jn < $tm or
$dn == $em and $jn == $tm and $hn <= $hm));
}
}
}
}
function e2__fruitful_neighbours_with_ymd_($gm, $wm = false, $um = false)
{
global $_db, $_config;
list($im, $om) = s1($gm, $wm, $um);
$pm = SECONDS_IN_A_DAY;
if ($um === false) {
$pm = SECONDS_IN_A_MONTH;
}
if ($wm === false) {
$pm = SECONDS_IN_A_YEAR;
}
$cf = $vf = null;
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` < '" .
($om - $pm) .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()) .
"ORDER BY Stamp DESC",
"get previous fruitful neighbour with ymd"
);
while ($bf = mysqli_fetch_array($_db["result"], MYSQLI_ASSOC)) {
list($dn, $jn, $hn) = explode("/", y1("Y/n/j", $bf["Stamp"], ia($bf)));
$yf = $gm * 10000 + ($wm ? $wm * 100 : 0) + ($um ? $um : 0);
$nf = $dn * 10000 + ($wm ? $jn * 100 : 0) + ($um ? $hn : 0);
if ($nf < $yf) {
$cf = gmmktime(0, 0, 0, (int) $jn, (int) $hn, (int) $dn);
break;
}
}
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` > '" .
($im + $pm) .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()) .
"ORDER BY Stamp",
"get next fruitful neighbour with ymd"
);
while ($bf = mysqli_fetch_array($_db["result"], MYSQLI_ASSOC)) {
list($dn, $jn, $hn) = explode("/", y1("Y/n/j", $bf["Stamp"], ia($bf)));
$yf = $gm * 10000 + ($wm ? $wm * 100 : 0) + ($um ? $um : 0);
$nf = $dn * 10000 + ($wm ? $jn * 100 : 0) + ($um ? $hn : 0);
if ($nf > $yf) {
$vf = gmmktime(0, 0, 0, (int) $jn, (int) $hn, (int) $dn);
break;
}
}
return [$cf, $vf];
}
function e2__parameters_with_timestamp_($mf)
{
list(
$parameters["year"],
$parameters["month"],
$parameters["day"],
) = explode("/", gmdate("Y/m/d", $mf));
return $parameters;
}
function w($wn, $ff, $dn = false, $jn = false)
{
$tn = [];
$df = [];
foreach ($ff as $k3 => $zy) {
$r["href"] = eq("e2m_note", ["*note" => $zy]);
$r["time"] = [(int) $zy["Stamp"], ia($zy)];
$r["last-modified"] = [(int) min($zy["LastModified"], time()), ia($zy)];
$r["favourite?"] = (bool) ($zy["IsFavourite"] && $zy["IsPublished"]);
$sf = ff($zy);
$r["draft?"] = $sf === "draft";
$r["scheduled?"] = $sf === "scheduled";
$r["public?"] = $sf === "public";
$r["hidden?"] = $sf === "hidden";
if (
array_key_exists("SourceNoteURL", $zy) and
@$zy["SourceNoteURL"] != ""
) {
$r["href"] = $zy["SourceNoteURL"];
$r["href-original"] = $zy["SourceNoteURL"];
}
if (
$dn and
$jn and
((int) $dn) . "/" . ((int) $jn) ==
y1("Y/n", $zy["Stamp"], ia($zy)) or
$dn and !$jn and (int) $dn == y1("Y", $zy["Stamp"], ia($zy)) or
!$dn and !$jn
) {
$tn[] = $r;
$df[] = str_replace("\n", " ", $zy["Title"]);
}
}
if (Log::$a) {
__log("Will do typography");
}
if ($wn) {
$af = implode("\n", $df);
$af = ay(htmlspecialchars($af, ENT_NOQUOTES, "UTF-8"));
$df = explode("\n", $af);
}
foreach ($tn as $k3 => $x3) {
$tn[$k3]["title"] = $df[$k3];
}
$tn = array_reverse($tn);
return $tn;
}
function u()
{
global $_config;
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()),
"get all notes list years with notes"
);
$h3 = qm();
$qf = [];
foreach ($h3 as $lf) {
$zf = (int) y1("Y", $lf["Stamp"], ia($lf));
$qf[$zf] = true;
}
$qf = array_keys($qf);
sort($qf);
return $qf;
}
function i($gm)
{
global $_config;
list($kf, $xf) = s1($gm);
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` BETWEEN '" .
$kf .
"' AND '" .
$xf .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()),
"get all notes for the year " . $gm . " to list months with notes"
);
$h3 = qm();
$ef = [];
foreach ($h3 as $lf) {
if (((int) $gm) == y1("Y", $lf["Stamp"], ia($lf))) {
$rf = (int) y1("n", $lf["Stamp"], ia($lf));
$ef[$rf] = true;
}
}
$ef = array_keys($ef);
sort($ef);
return $ef;
}
function o($gm, $wm)
{
global $_config;
list($tf, $jf) = s1($gm, $wm);
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` BETWEEN '" .
$tf .
"' AND '" .
$jf .
"' " .
"AND `Stamp` <= '" .
time() .
"' " .
df(ys()),
"get all notes for the month " .
$wm .
" of the year " .
$gm .
" to list days with notes"
);
$h3 = qm();
$hf = [];
foreach ($h3 as $lf) {
if (
((int) $gm) . "/" . ((int) $wm) ==
y1("Y/n", $lf["Stamp"], ia($lf))
) {
$gf = (int) y1("j", $lf["Stamp"], ia($lf));
$hf[$gf] = true;
}
}
$hf = array_keys($hf);
sort($hf);
return $hf;
}
function p()
{
$wf = cv("end");
return eq("e2m_day", [
"year" => y1("Y", $wf["stamp"], $wf["timezone"]),
"month" => y1("m", $wf["stamp"], $wf["timezone"]),
"day" => y1("d", $wf["stamp"], $wf["timezone"]),
]);
}
function cv($uf)
{
global $_config;
$if_ = "p1";
$gn = ys();
if (!$gn) {
$if_ = "p1v1";
}
$of = USER_DIR . CACHES_DIRNAME . $uf . "-stamp-" . $if_ . ".e2time.psa";
if (CACHE_EDGE_TIMEINFO and is_file($of)) {
$vb = @unserialize(file_get_contents($of));
}
if (is_array(@$vb)) {
return $vb;
} else {
$vb = ["stamp" => time(), "timezone" => pa()];
$pf = $uf == "end" ? " DESC" : "";
sm(
"SELECT `Stamp`, `Offset`, `IsDST` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `Stamp` <= '" .
time() .
"' " .
df($gn) .
"ORDER BY `Stamp`" .
$pf .
" LIMIT 1",
"get " . $uf . " timestamp"
);
$h3 = qm();
if (count($h3)) {
$vb = ["stamp" => $h3[0]["Stamp"], "timezone" => ia($h3[0])];
if (CACHE_EDGE_TIMEINFO) {
e3($of, serialize($vb));
}
return $vb;
}
return $vb;
}
}
function vv($url, $c2 = false)
{
if ($_SERVER["HTTP_USER_AGENT"] === E2_UA_STRING) {
if (Log::$a) {
__log("Spawn not allowed when requested by Aegea itself");
}
return false;
}
if (Log::$a) {
__log(
"Spawn: Curl " . $url . " using " . ($c2 ? "post" : "get") . "..."
);
}
if (function_exists("curl_init")) {
$v2 = curl_init();
$b2 = !ini_get("open_basedir");
$b2 = ($b2 and !$c2);
curl_setopt_array($v2, [
CURLOPT_URL => $url,
CURLOPT_POST => $c2,
CURLOPT_POSTREDIR => false,
CURLOPT_POSTFIELDS => "",
CURLOPT_CONNECTTIMEOUT => 300,
CURLOPT_TIMEOUT => 1,
CURLOPT_MAXREDIRS => 1,
CURLOPT_COOKIE => fs(),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => $b2,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_USERAGENT => E2_UA_STRING,
]);
$content = curl_exec($v2);
$y2 = curl_errno($v2);
$n2 = curl_error($v2);
$m2 = curl_getinfo($v2);
curl_close($v2);
if (Log::$a) {
__log(
"Spawn: Curl returns: [" .
print_r($m2, true) .
"] [" .
$content .
"], (errno=" .
$y2 .
", errstr=" .
$n2 .
")..."
);
}
return $m2;
} else {
if (Log::$a) {
__log("Spawn: Curl functions are not available");
}
}
}
function e2_check_timeout()
{
static $f2;
if (is_null($f2)) {
$d2 = ini_get("max_execution_time");
if ($d2) {
$f2 = time() + $d2 - 5;
} else {
$f2 = 0;
}
}
return $f2 == 0 ? true : $f2 >= time();
}
function e2_write_dump_header($s2)
{
$m2 =
'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";' .
PHP_EOL .
"SET AUTOCOMMIT=0;" .
PHP_EOL .
"START TRANSACTION;" .
PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;" .
PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;" .
PHP_EOL .
"/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;" .
PHP_EOL .
"/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;" .
PHP_EOL .
"/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;" .
PHP_EOL .
"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=NO_AUTO_VALUE_ON_ZERO */;" .
PHP_EOL .
"/*!40101 SET NAMES utf8 */;" .
PHP_EOL .
"/*!50503 SET NAMES utf8mb4 */;" .
PHP_EOL .
"";
fwrite($s2, $m2);
return true;
}
function e2_write_dump_footer($s2)
{
$a2 = "COMMIT;" . PHP_EOL;
$a2 .=
"/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;" .
PHP_EOL .
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;" .
PHP_EOL .
"/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;" .
PHP_EOL .
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;" .
PHP_EOL .
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;" .
PHP_EOL .
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;" .
PHP_EOL;
fwrite($s2, $a2);
return true;
}
function e2_get_table_definition($q2, $l2)
{
$z2 = null;
$h3 = mysqli_query($q2, "SHOW CREATE TABLE `{$l2}`");
if ($h3) {
$k2 = mysqli_fetch_array($h3);
$z2 = $k2["Create Table"];
}
return $z2;
}
function e2_write_table_definition($s2, $q2, $l2)
{
$x2 = e2_get_table_definition($q2, $l2);
if (e2_check_timeout() && $x2) {
fwrite($s2, $x2);
fwrite($s2, ";");
fwrite($s2, PHP_EOL . PHP_EOL);
return true;
}
return false;
}
function e2_get_table_data($q2, $l2, $t3, $limit)
{
$e2_ = "SELECT * FROM `{$l2}` LIMIT {$t3}, {$limit}";
$h3 = mysqli_query($q2, $e2_);
if (!$h3) {
return false;
}
$r2 = "";
$t2 = "INSERT INTO `{$l2}` VALUES";
while ($j2 = mysqli_fetch_row($h3)) {
$h2 = [];
foreach ($j2 as $vv) {
$h2[] = is_null($vv)
? "NULL"
: "'" . mysqli_real_escape_string($q2, $vv) . "'";
}
$r2 .= $t2 . "(" . join(", ", $h2) . ");" . PHP_EOL;
}
return $r2;
}
function e2_table_disable_keys($l2)
{
return "ALTER TABLE `{$l2}` DISABLE KEYS;" . PHP_EOL;
}
function e2_table_enable_keys($l2)
{
return "ALTER TABLE `{$l2}` ENABLE KEYS;" . PHP_EOL;
}
function e2_get_total_records($q2, $l2)
{
$k3 = mysqli_fetch_row(mysqli_query($q2, "SELECT COUNT(*) FROM `{$l2}`"));
return $k3[0];
}
function e2_backup_select_chuck_size_for_table_($l2)
{
$limit = 5000;
if (substr($l2, -7) === "Actions") {
$limit = 50000;
}
if (substr($l2, -7) === "Aliases") {
$limit = 20000;
}
if (substr($l2, -7) === "NotesKeywords") {
$limit = 50000;
}
if (Log::$a) {
__log("Backup: chunk size " . (int) $limit);
}
return $limit;
}
function e2_write_table_data($s2, $q2, $l2, $subset)
{
$g2 = e2_get_total_records($q2, $l2);
$t3 = 0;
$limit = e2_backup_select_chuck_size_for_table_($l2);
$h3 = true;
$w2 = 20000;
$u2 = 30;
if ($g2) {
$i2 = e2_table_disable_keys($l2);
fwrite($s2, $i2);
}
$r2 = "INSERT INTO `{$l2}` VALUES";
$o2 = $g2;
while ($o2 > 0) {
$e2_ = "SELECT * FROM `{$l2}` ";
if ((int) $subset > 0) {
$e2_ .= "WHERE `SubsetID` = {$subset} ";
}
$e2_ .= "ORDER BY `ID` LIMIT {$t3}, {$limit}";
$h3 = mysqli_query($q2, $e2_);
$p2 = mysqli_num_rows($h3);
if (!$h3 || !e2_check_timeout()) {
$h3 = false;
break;
}
$cd = [];
$vd = 0;
$bd = 0;
while ($j2 = mysqli_fetch_row($h3)) {
if (!e2_check_timeout()) {
$h3 = false;
break;
}
$p2--;
$fb = [];
foreach ($j2 as $vv) {
$fb[] = is_null($vv)
? "NULL"
: "'" . mysqli_real_escape_string($q2, $vv) . "'";
}
$zb = "(" . join(", ", $fb) . ")";
$vd += strlen($zb);
$cd[] = $zb;
$bd++;
if ($vd >= $w2 || $bd >= $u2 || $p2 == 0) {
$e2_ = $r2 . join(", ", $cd) . ";";
fwrite($s2, $e2_);
fwrite($s2, PHP_EOL);
$vd = 0;
$bd = 0;
$cd = [];
}
}
$t3 += $limit;
$o2 -= $limit;
}
if ($g2) {
$yd = e2_table_enable_keys($l2);
fwrite($s2, $yd);
}
return $h3;
}
function e2_backup($q2, $nd, $subset, $md)
{
$fd = tmpfile();
e2_write_dump_header($fd);
if (Log::$a) {
__log("Backup: wrote header");
}
$dd = true;
foreach ($nd as $l2) {
if ((int) $subset > 0) {
if (Log::$a) {
__log("Backup: table " . $l2 . ", subset " . $subset);
}
} else {
if (Log::$a) {
__log("Backup: table " . $l2 . ", all subsets");
}
}
$sd = e2_write_table_definition($fd, $q2, $l2);
if (Log::$a) {
__log("Backup: wrote table definition with result " . @(int) $sd);
}
$ad = e2_write_table_data($fd, $q2, $l2, $subset);
if (Log::$a) {
__log("Backup: wrote table data with result " . @(int) $ad);
}
$dd = $sd && $ad;
if ($dd === false) {
break;
}
}
if (Log::$a) {
__log("Backup: wrote data with running == " . (int) $dd);
}
if ($dd) {
e2_write_dump_footer($fd);
fseek($fd, 0);
$s2 = fopen($md, "w+");
while ($dd && ($zb = fread($fd, 1024))) {
if (e2_check_timeout()) {
fwrite($s2, $zb);
} else {
$dd = false;
}
}
fclose($s2);
}
fclose($fd);
return $dd;
}
function xv()
{
global $settings, $_lang, $_config, $_strings;
if (Log::$a) {
__log("Blog information");
}
$qd["author"] = htmlspecialchars(rv(), ENT_NOQUOTES, "UTF-8");
if (array_key_exists("blog_subtitle", $settings)) {
$ld = zy($settings["blog_subtitle"], "full");
$zd = $ld["text-final"];
$qd["subtitle"] = $zd;
$qd["subtitle-format-info"] = $ld["meta"];
m2(@$ld["meta"]["links-required"]);
}
$qd["title"] = htmlspecialchars(ev(), ENT_NOQUOTES, "UTF-8");
$qd["userpic-set?"] = false;
$qd["userpic-changeable?"] = ys();
if ($qd["userpic-href"] = tv()) {
$qd["userpic-set?"] = true;
$qd["userpic-large-href"] = tv("large");
$qd["userpic-square-href"] = tv("square");
$qd["userpic-changeable-href"] = $qd["userpic-href"];
} else {
unset($qd["userpic-href"]);
}
if (ys()) {
$qd["userpic-upload-action"] = eq("e2j_userpic_upload");
$qd["userpic-remove-action"] = eq("e2j_userpic_remove");
}
$qd["href"] = eq("e2m_frontpage", ["page" => 1]);
$qd["rss-href"] = eq("e2m_rss");
$qd["jsonfeed-href"] = eq("e2m_json");
$qd["language"] = $_lang;
$qd["show-follow-button?"] = false;
$qd["license-expired?"] = false;
$xd = [time(), pa()];
$ed = n1("Y", $xd[0]);
$qd["now"] = $xd;
$rd = $ed;
$td = cv("start");
if (array_key_exists("stamp", $td)) {
$rd = n1("Y", $td["stamp"]);
$qd["start-time"] = [(int) $td["stamp"], $td["timezone"]];
}
$jd = false;
$hd = nf(true, true);
if ($hd !== null) {
if (ys()) {
$gd = nf(true, false);
if ($gd !== null) {
$jd = $hd + $gd == 0;
}
} else {
$jd = $hd == 0;
}
}
$qd["notes-count"] = (int) $hd;
if ($qd["notes-count"] > 0) {
$qd["selected-href"] = eq("e2m_favourites", ["page" => 1]);
$qd["most-commented-href"] = eq("e2m_most_commented", ["page" => 1]);
$qd["popular-href"] = eq("e2m_popular", ["page" => 1]);
$qd["calendar-href"] = p();
$qd["random-note-href"] = sf();
}
$qd["virgin?"] = $jd;
$wd = $_config["years_range_separator"]
? $_config["years_range_separator"]
: $_strings["gs--range-separator"];
$qd["years-range"] = $rd . ($rd == $ed ? "" : $wd . $ed);
if (AeEnv::$w) {
$qd["parent-site-href"] = substr(
AeEnv::$w,
(int) strpos("/", AeEnv::$w)
);
}
return $qd;
}
function ev()
{
global $settings, $_strings;
if (
array_key_exists("blog_title", $settings) and
trim($settings["blog_title"]) != ""
) {
return trim($settings["blog_title"]);
} else {
return $_strings["e2--default-blog-title"];
}
}
function rv()
{
global $settings, $_strings;
if (
array_key_exists("author", $settings) and
trim($settings["author"]) != ""
) {
return trim($settings["author"]);
} else {
return $_strings["e2--default-blog-author"];
}
}
function tv($size = "")
{
global $_config;
$ud = false;
$id = $_config["path_media"] . USERPIC_DIRNAME;
if (is_file($id . "[email protected]")) {
$ud = "[email protected]";
} elseif (is_file($id . "[email protected]")) {
$ud = "[email protected]";
}
if ($size == "large" and is_file($id . "[email protected]")) {
$ud = "[email protected]";
} elseif ($size == "square" and is_file($id . "[email protected]")) {
$ud = "[email protected]";
}
if ($ud === false) {
return false;
}
$od = $id . $ud;
$pd = AeEnv::$o . USERPIC_DIRNAME . $ud;
$cs = stat($od);
if ($cs["mtime"]) {
$pd .= "?" . $cs["mtime"];
}
return $pd;
}
function jv()
{
global $_config, $_stopwatch, $vs;
$bs = round(dq() - $_stopwatch, 3);
return [
"show?" => $_config["display_stat"] > (int) !ys(),
"generation-time" => str_replace(".", ",", $bs),
"peak-memory-mb" => str_replace(
".",
",",
round((memory_get_peak_usage() / 1024 / 1024) * 100) / 100
),
"db-query-count" => (int) @$vs,
];
}
function e2m_info()
{
global $settings, $_template;
if (!isset($_template)) {
kf();
}
$ys = [
"E2_VERSION" => E2_VERSION,
"E2_RELEASE" => E2_RELEASE,
"E2_UA_STRING" => E2_UA_STRING,
"E2_EDITION" => defined("E2_EDITION") ? E2_EDITION : "0",
"---",
"PHP_VERSION" => PHP_VERSION,
"---",
"installed" => yn() !== null,
"server_name" => AeEnv::$server,
"folder_on_server" => AeEnv::$w,
"---",
"default formatter" => DEFAULT_FORMATTER,
"---",
"theme" => $settings["template"],
"---",
"Olba name" => $_template["name"],
"Olba stack" => $_template["stack"],
"---",
"Neasden" => substr(
md5(file_get_contents("system/library/neasden/Interpreter.php")),
0,
4
),
"---",
];
echo "<pre>";
foreach ($ys as $k3 => $x3) {
if ($x3 == "---") {
echo "\n";
continue;
}
echo str_pad($k3, 24);
echo '\'';
print_r($x3);
echo '\'';
echo "\n";
}
echo "</pre>";
die();
}
function hv($s)
{
global $_config;
if (@$_config["broadcast_url"] and !$s["IsExternal"]) {
if ($_config["log_broadcast"]) {
Log::$a = true;
if (Log::$a) {
qn("broadcast");
}
}
if (Log::$a) {
__log("Broadcast-async note: " . $s["Title"]);
}
$url = eq("e2m_note_broadcast", ["*note" => $s]);
if (Log::$a) {
__log("Broadcast will spawn url: " . $url);
}
vv($url);
}
}
function gv($ns)
{
global $_config;
if (!$ns) {
return false;
}
$url = $_config["broadcast_url"];
$url .= "?src=" . urlencode($ns);
if ($_config["log_broadcast"]) {
Log::$a = true;
if (Log::$a) {
qn("broadcast");
}
}
if (Log::$a) {
__log("Broadcast: Curl " . $url . "...");
}
if (function_exists("curl_init")) {
$v2 = curl_init();
$b2 = !ini_get("open_basedir");
curl_setopt_array($v2, [
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 300,
CURLOPT_TIMEOUT => 1,
CURLOPT_MAXREDIRS => 1,
CURLOPT_COOKIE => fs(),
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => $b2,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_USERAGENT => E2_UA_STRING,
]);
$content = curl_exec($v2);
$y2 = curl_errno($v2);
$n2 = curl_error($v2);
$m2 = curl_getinfo($v2);
curl_close($v2);
if (Log::$a) {
__log(
"Broadcast: Curl returns: [" .
print_r($m2, true) .
"] [" .
$content .
"], (errno=" .
$y2 .
", errstr=" .
$n2 .
")..."
);
}
if ($y2 === 0) {
return true;
}
} else {
if (Log::$a) {
__log("Spawn: Curl functions are not available");
}
}
return false;
}
function wv($s)
{
if (!$s) {
return false;
}
$ns = eq("e2m_note_json", ["*note" => $s]);
return gv($ns);
}
function e2m_note_broadcast($parameters = [])
{
global $_config;
if (@$_config["broadcast_url"]) {
if (array_key_exists("*note", $parameters)) {
$ns = eq("e2m_note_json", ["*note" => $parameters["*note"]]);
} elseif (array_key_exists("alias", $parameters)) {
$ns = eq("e2m_note_json", ["alias" => $parameters["alias"]]);
}
if (gv($ns)) {
die("Broadcasted.");
} else {
die("Could not broadcast.");
}
} else {
return e2m_error404();
}
}
function e2_cache_filename_with_id_($ey, $if_)
{
return str_replace("*", $ey, $if_);
}
function e2_note_cache_filename_with_id_($ey)
{
return e2_cache_filename_with_id_($ey, USER_DIR . CACHE_FILENAMES_NOTES);
}
function e2_drop_caches_for_note_($note_id, $ms)
{
if (is_numeric($note_id)) {
if (Log::$a) {
__log("Caches: Drop caches for note id " . $note_id);
}
@unlink(e2_note_cache_filename_with_id_($note_id));
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments"));
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments-author"));
} else {
bq(USER_DIR . CACHE_FILENAMES_NOTES);
bq(USER_DIR . CACHE_FILENAMES_NOTES_COMMENTS);
bq(USER_DIR . CACHE_FILENAMES_NOTES_COMMENTS_AUTHOR);
}
vb();
if ($ms !== false) {
bb();
bq(USER_DIR . CACHE_FILENAMES_NOTES_RELATED);
bq(USER_DIR . CACHE_FILENAMES_POPULAR_WITH_TAG);
bq(USER_DIR . CACHE_FILENAMES_TAG);
bq(USER_DIR . CACHE_FILENAMES_TAG_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_POPULAR);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_FRONTPAGE_FEED);
@unlink(USER_DIR . CACHE_FILENAME_FULLLIST);
@unlink(USER_DIR . CACHE_FILENAME_TAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_FULL);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR_FULL);
}
if ($ms !== true) {
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
}
@unlink(USER_DIR . CACHE_FILENAME_LASTMODIFIEDS);
}
function e2_drop_caches_for_tag_($fs)
{
if (is_numeric($fs)) {
@unlink(
e2_cache_filename_with_id_($fs, USER_DIR . CACHE_FILENAMES_TAG)
);
@unlink(
e2_cache_filename_with_id_(
$fs,
USER_DIR . CACHE_FILENAMES_TAG_AUTHOR
)
);
} else {
bq(USER_DIR . CACHE_FILENAMES_TAG);
bq(USER_DIR . CACHE_FILENAMES_TAG_AUTHOR);
}
@unlink(USER_DIR . CACHE_FILENAME_FAVTAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_FULL);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR);
@unlink(USER_DIR . CACHE_FILENAME_TAGS_AUTHOR_FULL);
}
function cb()
{
if (Log::$a) {
__log("Caches: Drop notes caches");
}
e2_drop_caches_for_note_(null, null);
}
function vb()
{
if (Log::$a) {
__log("Caches: Drop notes counts cache");
}
bq(USER_DIR . CACHE_FILENAMES_NOTES_COUNTS);
}
function bb()
{
if (Log::$a) {
__log("Caches: Drop egde time info cache");
}
bq(USER_DIR . CACHE_FILENAMES_EDGE_TIMEINFO);
}
function e2_drop_all_kinds_of_cache()
{
if (Log::$a) {
__log("Caches: Drop all kinds of caches");
}
bq(USER_DIR . CACHES_DIRNAME . "*");
return true;
}
function e2m_comment($parameters = [])
{
z1(eq("e2m_note", $parameters));
}
function e2m_comment_edit($parameters = [])
{
return yb("edit", $parameters);
}
function yb($ds, $parameters = [])
{
global $_strings;
$ss = $as_ = $_strings["pt--new-comment"];
$qs = "new";
if ($ds == "edit") {
$ls = e2_commentrec_with_parameters_($parameters);
$zs = $_strings["fb--save-changes"];
$zy = $ls["noterec"];
$ss = $as_ = $_strings["pt--edit-comment"];
$ks = mb($zy, $ls, $parameters["comment-number"]);
if (!$ls) {
return e2m_error404();
}
$xs = [
".note-id" => $ls["NoteID"],
".comment-id" => $ls["ID"],
".comment-number" => $parameters["comment-number"],
".already-subscribed?" => false,
".gip" => $ls["GIP"],
"create:edit?" => false,
"form-action" => eq("e2s_comment_process"),
"submit-text" => $zs,
"show-subscribe?" => true,
"subscribe?" => (bool) $ls["IsSubscriber"],
"name" => htmlspecialchars($ls["AuthorName"], ENT_COMPAT, "UTF-8"),
"email" => htmlspecialchars(
$ls["AuthorEmail"],
ENT_COMPAT,
"UTF-8"
),
"text" => htmlspecialchars($ls["Text"], ENT_COMPAT, "UTF-8"),
"email-field-name" => a(),
"email-fields-revealed?" => true,
];
if ("" != trim($ls["IP"])) {
$xs["ip"] = $ls["IP"];
}
}
$vb = [
"title" => $ss,
"heading" => $as_,
"form" => "form-comment",
"form-comment" => $xs,
];
if (!empty($ks)) {
$vb["comments"] = ["each" => ["only" => $ks]];
}
return $vb;
}
function e2m_comment_reply($parameters = [])
{
global $_strings;
$ls = e2_commentrec_with_parameters_($parameters);
if (!$ls) {
return e2m_error404();
}
$zy = $ls["noterec"];
$ks = mb($zy, $ls, $parameters["comment-number"]);
$ks["replying?"] = (bool) true;
$es = ($ls["Reply"] == "" or !$ls["IsReplyVisible"]);
$ss = $es
? $_strings["pt--reply-to-comment"]
: $_strings["pt--edit-reply-to-comment"];
$rs = [
".note-id" => $zy["ID"],
".comment-id" => $ls["ID"],
".reply-action" => $es ? "new" : "edit",
"form-action" => eq("e2s_comment_edit_reply"),
"submit-text" => $es
? $_strings["fb--publish"]
: $_strings["fb--save-changes"],
"create:edit?" => (bool) $es,
"reply-text" => htmlspecialchars($ls["Reply"], ENT_COMPAT, "UTF-8"),
"emailing-possible?" => MAIL_ENABLED,
"mail-back?" => (bool) $es,
];
return [
"title" => $ss,
"heading" => $ss,
"comments" => ["each" => ["only" => $ks]],
"form" => "form-comment-reply",
"form-comment-reply" => $rs,
];
}
function e2m_comment_delete($parameters = [])
{
global $_config;
$ls = e2_commentrec_with_parameters_($parameters);
$note_id = $ls["NoteID"];
if (!$ls) {
return e2m_error404();
}
e2_drop_caches_for_note_($note_id, true);
@unlink(USER_DIR . "/last-comment.psa");
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
((int) $ls["ID"]) .
"'"
);
k1();
}
function e2m_comment_reply_delete($parameters = [])
{
global $_strings, $settings, $_config;
$ls = e2_commentrec_with_parameters_($parameters);
if (!$ls) {
return e2m_error404();
}
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Comments` SET " .
"`Reply`='', " .
"`IsReplyFavourite`='0' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
((int) $ls["ID"])
);
k1();
}
function e2m_unsubscribe($parameters)
{
global $_strings, $_config;
$pf = "ORDER BY `ID` DESC";
$ts = false;
$zy = $parameters["*note"];
$note_id = $zy["ID"];
$js = $parameters["unsubscribe-email"];
$hs = $parameters["unsubscribe-key"];
$js = str_replace(" ", "+", $js);
if ($note_id) {
sm(
"SELECT `ID`, `Stamp` FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
$note_id .
" " .
"AND `IsSubscriber`=1 " .
"AND `AuthorEmail`='" .
lm($js) .
"' " .
$pf,
"get subscribers comments ids"
);
$h3 = qm();
if (count($h3) < 1) {
$vb["unsubscribe"]["error-message"] =
$_strings["gs--you-are-not-subscribed"];
} else {
$gs = @$h3[0];
$ws = md5($gs["ID"] . $gs["Stamp"] . "x");
if ($hs == $ws) {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Comments` " .
"SET `IsSubscriber`=0 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
$note_id .
" " .
"AND `AuthorEmail` = '" .
lm($js) .
"'",
"unsubscribe"
);
$ts = true;
$vb["unsubscribe"]["note-title"] = ay(
htmlspecialchars($zy["Title"], ENT_COMPAT, "UTF-8")
);
$vb["unsubscribe"]["note-href"] = eq("e2m_note", [
"*note" => $zy,
]);
}
if (!$ts) {
$vb["unsubscribe"]["error-message"] =
$_strings["gs--unsubscription-didnt-work"];
}
}
} else {
$vb["unsubscribe"]["error-message"] = $_strings["gs--post-not-found"];
}
if ($ts) {
$ss = $_strings["pt--unsubscription-done"];
} else {
$ss = $_strings["pt--unsubscription-failed"];
}
$vb["unsubscribe"]["success?"] = $ts;
$vb["title"] = $ss;
$vb["heading"] = $ss;
return $vb;
}
function e2m_comment_flag($parameters)
{
nb($parameters);
z1(eq("e2m_note", $parameters));
}
function e2s_comment_flag_ajax($parameters)
{
g1([
"flag-name" => "comment",
"candy-name" => "e2s_comment_flag_ajax",
"parameters" => $parameters,
"flipping-function" => function () use ($parameters) {
nb($parameters);
},
"redirect-candy" => "e2m_note",
]);
}
function nb($parameters)
{
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_note", $parameters));
}
od();
$ls = e2_commentrec_with_parameters_($parameters);
$note_id = $ls["NoteID"];
if (!$ls) {
throw new AeException("Comment record not cound from parameters");
}
e2_drop_caches_for_note_($note_id, true);
fm(bl(), "Comments", [
"ID" => $ls["ID"],
$parameters["flag"] => (int) ($parameters["value"] == 1),
]);
}
function e2s_comment_process()
{
global $_strings;
$us = true;
$is = "";
try {
$note_id = rb();
} catch (AeFormIncompleteException $e) {
hb($_strings["er--name-email-text-required"], E2E_USER_ERROR);
z1(eq("e2m_note", ["*note" => wm($e->note_id)]));
} catch (AeFormNoteNotCommentableException $e) {
$us = false;
$os = $_strings["gs--comment-post-not-commentable"];
$ps = $_strings["gs--comment-post-not-commentable-description"];
$is = $e->comment_text;
} catch (AeFormDuplicateCommentException $e) {
$us = false;
$os = $_strings["gs--comment-double-post"];
$ps = $_strings["gs--comment-double-post-description"];
$is = $e->comment_text;
} catch (AeFormCommentTooLongException $e) {
$us = false;
$os = $_strings["gs--comment-too-long"];
$ps = $_strings["gs--comment-too-long-description"];
$is = $e->comment_text;
} catch (AeFormCommentIsSpamSuspectException $e) {
$us = false;
$os = $_strings["gs--comment-spam-suspect"];
$ps = $_strings["gs--comment-spam-suspect-description"];
$is = $e->comment_text;
}
if ($us) {
if ($note_id) {
z1(eq("e2m_note", ["*note" => wm($note_id)]));
} else {
z1();
}
} else {
$vb["title"] = $os;
$vb["heading"] = $os;
$vb["form"] = "form-unaccepted-comment";
$vb["form-unaccepted-comment"] = [
"reason" => $ps,
"text" => @htmlspecialchars($is, ENT_COMPAT, "UTF-8"),
];
return $vb;
}
die();
}
function e2s_comment_edit_reply()
{
global $_config;
od();
$ca = @$_POST["text"];
if (trim($ca) == "") {
$ca = "";
}
$note_id = @$_POST["note-id"];
$zy = wm($note_id);
$qs = @$_POST["comment-id"];
$ls = fb($qs);
$va = isset($_POST["mail-back"]);
$ba = time();
if (@$_POST["reply-action"] == "new") {
$ya = time();
}
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments"));
@unlink(e2_note_cache_filename_with_id_($note_id . "-comments-author"));
if ($ls) {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Comments` SET " .
"`Reply`='" .
lm($ca) .
"', " .
(isset($ya) ? "`ReplyStamp`='" . $ya . "', " : "") .
"`ReplyLastModified`='" .
$ba .
"', " .
"`IsReplyVisible`='1' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
((int) $qs),
"update comment reply"
);
$na = eq("e2m_note", ["*note" => $zy]);
if ($va and $ca != "") {
$ma["comment-time"] = [$ls["Stamp"], pa()];
$ma["commenter"] = $ls["AuthorName"];
$ma["commenter-email"] = $ls["AuthorEmail"];
$ma["comment-text"] = $ls["Text"];
$ma["note-title"] = ay($zy["Title"]);
$ma["reply-time"] = [time(), pa()];
$ma["blog-author"] = rv();
$ma["note-href"] = $na;
$ma["comment-href"] = $na;
$ma["reply-text"] = $ca;
if (1) {
$fa = kn("comment-reply", $ma);
$da = e2l_get_string("em--comment-reply", $ma);
$sa = $ls["AuthorEmail"];
$aa = "From: " . xn();
en($sa, $da, $fa, $aa);
}
if (1) {
unset($ma["commenter-email"]);
$aa = "From: " . xn();
foreach (kb($zy, $ls["AuthorEmail"]) as $qa) {
$la = $qa["AuthorEmail"];
$za = md5($qa["ID"] . $qa["Stamp"] . "x");
$ma["unsubscribe-href"] = eq("e2m_unsubscribe", [
"*note" => $zy,
"unsubscribe-email" => $la,
"unsubscribe-key" => $za,
]);
$sa = $la;
$fa = kn("comment-reply-to-public", $ma);
$da = e2l_get_string(
"em--comment-reply-to-public-subject",
$ma
);
en($sa, $da, $fa, $aa);
}
}
}
z1($na);
} else {
k1();
}
die();
}
function mb($zy, $ls, $ka)
{
global $_config;
if (Log::$a) {
__log("Package comment " . $ls["ID"] . "...");
}
if ($zy === null) {
$zy = wm($ls["NoteID"]);
}
$ma["number"] = $ka;
$xa = !empty($ls["IsGIPUsed"]);
$ma["gip-used?"] = $xa;
$ma["gip"] = $ma["gip-used?"] ? $ls["GIP"] : "";
$ma["name"] = htmlspecialchars($ls["AuthorName"], ENT_NOQUOTES, "UTF-8");
$ma["userpic-set?"] = false;
if ($xa) {
$ea = AVATARS_DIRNAME . $ls["GIP"] . "-" . $ls["GIPAuthorID"] . ".jpg";
if (is_file($_config["path_media"] . $ea)) {
$ma["userpic-set?"] = true;
$ma["userpic-href"] = AeEnv::$o . $ea;
}
}
$ma["name-href"] = "";
if (
$xa and
($ra = gy($ls["GIP"], $ls["GIPAuthorID"], $ls["AuthorProfileLink"]))
) {
$ma["name-href"] = $ra;
}
if (ys()) {
$ma["email"] = htmlspecialchars(
$ls["AuthorEmail"],
ENT_NOQUOTES,
"UTF-8"
);
if ("" != trim($ls["IP"])) {
$ma["ip"] = $ls["IP"];
}
}
$ma["author-name"] = rv();
$ma["new?"] = false;
$ma["important?"] = (bool) $ls["IsFavourite"];
$ma["reply-visible?"] = (bool) ($ls["IsVisible"] && $ls["IsReplyVisible"]);
$ma["reply-important?"] = (bool) $ls["IsReplyFavourite"];
$ma["spam-suspect?"] = (bool) $ls["IsSpamSuspect"];
$ta = [(int) $ls["Stamp"], ia($zy)];
$ma["time"] = $ta;
$ma["last-modified"] = $ta;
if ($ls["LastModified"]) {
$ma["last-modified"] = [(int) $ls["LastModified"], ia($zy)];
}
if ($ls["ReplyStamp"]) {
$ma["reply-time"] = [(int) $ls["ReplyStamp"], ia($zy)];
}
if ($ls["ReplyLastModified"]) {
$ma["reply-last-modified"] = [(int) $ls["ReplyLastModified"], ia($zy)];
}
if (ys()) {
$ma["subscriber?"] = (bool) $ls["IsSubscriber"];
$ma["new?"] = (bool) $ls["IsNew"];
$ma["first-new?"] = false;
if (!@$_config["read_only"]) {
$ma["important-toggle-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsFavourite",
"value" => !$ls["IsFavourite"],
]);
$ma["reply-important-toggle-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsReplyFavourite",
"value" => !$ls["IsReplyFavourite"],
]);
$ma["edit-href"] = eq("e2m_comment_edit", [
"*note" => $zy,
"comment-number" => $ka,
]);
$ma["removed-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsVisible",
"value" => 0,
]);
$ma["removed-reply-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsReplyVisible",
"value" => 0,
]);
$ma["replaced-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsVisible",
"value" => 1,
]);
$ma["replaced-reply-action"] = eq("e2s_comment_flag_ajax", [
"*note" => $zy,
"comment-number" => $ka,
"flag" => "IsReplyVisible",
"value" => 1,
]);
$ja = eq("e2m_comment_reply", [
"*note" => $zy,
"comment-number" => $ka,
]);
if ($ls["Reply"] == "" or !$ls["IsReplyVisible"]) {
$ma["reply-href"] = $ja;
} else {
$ma["edit-reply-href"] = $ja;
}
}
}
if (mb_strlen((string) @$ls["Text"]) > $_config["max_comment_length"]) {
$ls["Text"] = mb_substr($ls["Text"], 0, $_config["max_comment_length"]);
}
$ha = $zy["FormatterID"] === "raw" ? "neasden" : $zy["FormatterID"];
$ld = ly($ha, $ls["Text"], "simple");
$ma["text"] = $ld["text-final"];
$ma["reply"] = "";
$ma["replying?"] = (bool) false;
$ma["replied?"] =
(bool) (trim((string) @$ls["Reply"]) != "" && $ls["IsReplyVisible"]);
if ((string) $ls["Reply"] !== "") {
$ld = ly($zy["FormatterID"], $ls["Reply"], "full");
$ma["reply"] = $ld["text-final"];
}
if (Log::$a) {
__log("Comments: done");
}
return $ma;
}
function fb($ey)
{
global $_config;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
$ey .
"'"
);
$kb = qm();
if (count($kb) > 0) {
return $kb[0];
} else {
return false;
}
}
function db($s)
{
global $_strings, $_config, $settings;
if (@$_config["read_only"]) {
return null;
}
if (!xb($s)) {
return null;
}
$ga = ky();
if (!count($ga) and !empty($settings["comments"]["require_gip"])) {
return null;
}
$wa = (string) @$_COOKIE[x1("commenter_name")];
$ua = (string) @$_COOKIE[x1("commenter_email")];
$ia = (string) @$_COOKIE[x1("commenter_ph")];
$oa = false;
if ($ua and $ia) {
foreach (kb($s) as $qa) {
$ws = md5($qa["ID"] . $qa["Stamp"] . "x");
if ($qa["AuthorEmail"] == $ua and $ia == $ws) {
$oa = true;
break;
}
}
}
$zs = $_strings["fb--submit"];
$nn = q();
$xs = [
".note-id" => $s["ID"],
".comment-id" => "new",
".already-subscribed?" => (bool) $oa,
"cookie-name" => z($s["ID"]),
"cookie-value" => k(),
"email-field-name" => a(),
"nospam-field-name-part-1" => substr($nn, 0, 4),
"nospam-field-name-part-2" => substr($nn, 4),
"create:edit?" => true,
"form-action" => eq("e2s_comment_process"),
"submit-text" => $zs,
"show-subscribe?" => (bool) !$oa,
"emailing-possible?" => MAIL_ENABLED,
"subscribe?" => (bool) $oa,
"subscription-status" => $oa
? $_strings["gs--you-are-already-subscribed"]
: "",
"name" => htmlspecialchars($wa, ENT_COMPAT, "UTF-8"),
"email" => htmlspecialchars($ua, ENT_COMPAT, "UTF-8"),
"text" => "",
"email-comments-enabled?" => empty(
$settings["comments"]["require_gip"]
),
"gips" => [],
];
$pa = false;
$c1 = "";
foreach ($ga as $v1) {
if (!is_file(SYSTEM_DIR . "gips/" . $v1 . ".json")) {
continue;
}
$b1 = ty($v1);
$xs["gips"][$v1] = ry($v1);
if ($b1) {
$pa = true;
$y1 = wy($v1);
$c1 = $y1["GIP"];
$xs["name"] = htmlspecialchars(
$y1["AuthorName"],
ENT_COMPAT,
"UTF-8"
);
}
}
if (!$xs["email-comments-enabled?"] and !count($xs["gips"])) {
return false;
}
$n1 = count($xs["gips"]) === 0;
$xs["email-comments-only?"] = $n1;
$xs["email-fields-revealed?"] = ($n1 or !empty($wa) and !empty($ua));
$xs["logged-in?"] = $pa;
$xs["logged-in-gip"] = $c1;
$xs["logout-url"] = $pa
? eq("e2m_gip_sign_out", ["provider" => E2GIP::get_logout_key()])
: "";
return $xs;
}
function sb($note_id)
{
return qb($note_id, "`IsNew` = 1");
}
function ab($note_id)
{
return qb($note_id, "`IsVisible` = 1");
}
function qb($note_id, $m1)
{
global $_config;
if (!is_numeric($note_id)) {
return 0;
}
$f1 = 0;
sm(
"SELECT count(*) " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
$note_id .
" " .
"AND (" .
$m1 .
")",
"count comments"
);
$h3 = qm();
$h3 = (int) $h3[0]["count(*)"];
$f1 = $h3;
return (int) $f1;
}
function lb(AeDatabaseConfiguration $databaseConfiguration)
{
if (Log::$a) {
__log("Count new comments");
}
$d1 = 0;
$s1 = "";
sm(
"SELECT `NoteID`, `Text` FROM `" .
$databaseConfiguration->getPrefix() .
"Comments` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `IsNew`=1 ORDER BY `Stamp` DESC",
"count new comments for author menu"
);
$h3 = qm();
$d1 = count($h3);
while ($d1-- > 0) {
if ($zy = wm($h3[$d1]["NoteID"])) {
$s1 = eq("e2m_note", ["*note" => $zy]);
break;
}
}
$d1++;
return [(int) $d1, $s1];
}
function zb($note_id)
{
global $_config;
if (Log::$a) {
__log("Comments: getting comments for note " . $note_id);
}
sm(
"SELECT c.*, g.`AuthorProfileLink` " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` c " .
"LEFT JOIN `" .
$_config["db_table_prefix"] .
"GIPsSessions` g " .
"ON c.`SubsetID`=g.`SubsetID` " .
"AND c.`GIP`=g.`GIP` " .
"AND c.`GIPAuthorID`=g.`GIPAuthorID` " .
"WHERE c.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
@$note_id .
" " .
"ORDER BY `Stamp`",
"get comments including deleted"
);
$h3 = qm();
return $h3;
}
function kb($zy, $a1 = "")
{
global $_config;
$pf = "ORDER BY `ID` DESC";
$vb = $q1 = [];
sm(
"SELECT DISTINCT `ID`, `Text`, `IsSubscriber`, `IsVisible`, " .
"`AuthorName`, `AuthorEmail`, `Stamp` " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `NoteID`=" .
@$zy["ID"] .
" " .
"AND `IsSubscriber`=1 " .
"AND `IsVisible`=1 " .
"AND `AuthorEmail`!='" .
lm($a1) .
"' " .
$pf,
"get subscribers by note"
);
$h3 = qm();
foreach ($h3 as $qa) {
if (!in_array($qa["AuthorEmail"], $q1)) {
$vb[] = $qa;
}
$q1[] = $qa["AuthorEmail"];
}
return $vb;
}
function xb($zy, $l1 = NOTE_COMMENTABLE_NOW)
{
global $settings, $_config;
$z1 = true;
if (@$settings["comments"]["fresh_only"]) {
if (isset($_config["comment_freshness_days"])) {
if (
$zy["Stamp"] <
time() - $_config["comment_freshness_days"] * SECONDS_IN_A_DAY
) {
$z1 = false;
}
}
}
$k1 = $zy["IsCommentable"];
if ($l1 == NOTE_COMMENTABLE_NOW_CONDITIONALLY) {
$k1 = true;
}
return ff($zy) === "public" and $z1 and $k1;
}
function e2_commentrec_with_parameters_($parameters = [])
{
$zy = $parameters["*note"];
$x1 = zb($zy["ID"]);
$ls = @$x1[$parameters["comment-number"] - 1];
if ($ls) {
$ls["noterec"] = $zy;
return $ls;
}
}
function rb()
{
global $settings, $_config;
if (Log::$a) {
__log("Process comment form");
}
od();
$bn = a();
$note_id = $qs = $name = $js = $e1 = "";
if (array_key_exists("note-id", $_POST)) {
$note_id = trim(@$_POST["note-id"]);
}
if (array_key_exists("comment-id", $_POST)) {
$qs = trim(@$_POST["comment-id"]);
}
if (array_key_exists("comment-number", $_POST)) {
$ka = trim(@$_POST["comment-number"]);
}
if (array_key_exists("name", $_POST)) {
$name = trim(@$_POST["name"]);
}
if (array_key_exists($bn, $_POST)) {
$js = trim(@$_POST[$bn]);
}
if (array_key_exists("text", $_POST)) {
$e1 = trim(@$_POST["text"]);
}
if ($qs === "new") {
$r1 = hy();
if ($r1) {
$y1 = wy($r1);
$name = trim($y1["AuthorName"]);
$js = "";
$t1 = $y1["GIPAuthorID"];
}
} else {
if (array_key_exists("gip", $_POST)) {
$r1 = trim(@$_POST["gip"]);
}
}
$j1 =
(array_key_exists("already-subscribed", $_POST) and
$_POST["already-subscribed"] or
array_key_exists("subscribe", $_POST) and $_POST["subscribe"]);
$in = time();
if (!is_numeric($note_id)) {
throw new AeFormInconsistentException();
}
if (!is_numeric($qs) and $qs !== "new") {
throw new AeFormInconsistentException();
}
if ($qs !== "new" and !ys()) {
throw new AeFormInconsistentException();
}
if ($e1 == "" or !$r1 and ((string) $name === "" or (string) $js === "")) {
throw new AeFormIncompleteException($note_id);
}
if ($qs == "new" and !$r1) {
e1("commenter_name", $name);
e1("commenter_email", $js);
}
$h1 =
($qs === "new" and
(x() or e2_cookie_data_is_spam_suspicios_for_note_id_($note_id)));
if ($qs == "new") {
$g1 = @unserialize(file_get_contents(USER_DIR . "/last-comment.psa"));
if (md5($name . $js . $e1) == @$g1["md5"]) {
throw new AeFormDuplicateCommentException($e1);
}
if (
isset($_config["max_comment_length"]) and
strlen(@$_POST["text"]) > $_config["max_comment_length"]
) {
throw new AeFormCommentTooLongException($e1);
}
$zy = wm($note_id);
if ($qs == "new" and !xb($zy)) {
throw new AeFormNoteNotCommentableException($e1);
}
if ($h1) {
throw new AeFormCommentIsSpamSuspectException($e1);
}
}
e2_drop_caches_for_note_($note_id, true);
if ($qs == "new") {
$ls = [
"NoteID" => (int) $note_id,
"AuthorName" => $name,
"AuthorEmail" => $js,
"Text" => $e1,
"Reply" => "",
"IsVisible" => 1,
"IsAnswerAware" => 1,
"IsSubscriber" => (int) $j1,
"IsSpamSuspect" => (int) $h1,
"IsNew" => 1,
"Stamp" => (int) time(),
"LastModified" => (int) time(),
"IP" => lm(pd()),
"IsGIPUsed" => intval(!empty($r1) && !empty($t1)),
"GIP" => !empty($r1) ? lm($r1) : "",
"GIPAuthorID" => !empty($t1) ? lm($t1) : "",
];
$ls = mm(bl(), "Comments", $ls);
$qs = $ls["ID"];
$g1 = ["id" => $qs, "md5" => md5($name . $js . $e1)];
@e3(USER_DIR . "last-comment.psa", serialize($g1));
$w1 = md5($ls["ID"] . $ls["Stamp"] . "x");
e1("commenter_ph", $w1);
$zy = wm($note_id);
$na = eq("e2m_note", ["*note" => $zy]);
$ma["comment-time"] = [$in, pa()];
$ma["commenter"] = $name;
$ma["commenter-email"] = $js;
$ma["comment-text"] = $e1;
$ma["note-title"] = $zy["Title"];
$ma["note-href"] = $na;
$ma["comment-href"] = $na;
$ma["comments-disable-href"] = eq("e2s_note_flag", [
"*note" => $zy,
"flag" => "IsCommentable",
"value" => 0,
]);
$ma["reply-href"] = eq("e2m_comment_reply", [
"*note" => $zy,
"comment-number" => $ka,
]);
if (
isset($settings["author_email"]) and
@$settings["notifications"]["new_comments"]
) {
$fa = kn("comment-new-to-author", $ma);
$da = e2l_get_string("em--comment-new-to-author-subject", $ma);
$sa = $settings["author_email"];
$aa =
"From: " .
xn() .
"\r\n" .
"Reply-to: " .
$name .
" <" .
$js .
">";
en($sa, $da, $fa, $aa);
}
if (!$h1) {
unset($ma["commenter-email"]);
$aa = "From: " . xn();
foreach (kb($zy, $js) as $qa) {
$la = $qa["AuthorEmail"];
$za = md5($qa["ID"] . $qa["Stamp"] . "x");
$ma["unsubscribe-href"] = eq("e2m_unsubscribe", [
"*note" => $zy,
"unsubscribe-email" => $la,
"unsubscribe-key" => $za,
]);
$sa = $la;
$fa = kn("comment-new-to-public", $ma);
$da = e2l_get_string("em--comment-new-to-public-subject", $ma);
en($sa, $da, $fa, $aa);
}
}
} else {
$u1 = [
"ID" => $qs,
"Text" => $e1,
"IsVisible" => 1,
"IsSubscriber" => ((int) $j1),
"LastModified" => time(),
];
if (!empty($name)) {
$u1["AuthorName"] = $name;
}
if (!empty($js)) {
$u1["AuthorEmail"] = $js;
}
fm(bl(), "Comments", $u1);
}
return (int) $note_id;
}
define(
"E2_UA_STRING",
"Aegea " .
E2_RELEASE .
" (v" .
E2_VERSION .
(defined("E2_EDITION") ? "e" : "") .
")"
);
define("E2_MINIMUM_PHP", "5.6");
define("E2_MINIMUM_MYSQL", "5.6");
define("E2_MINIMUM_MARIADB", "10.1");
define("E2E_STRANGE_ERROR", 10);
define("E2E_USER_ERROR", 20);
define("E2E_PERMISSIONS_ERROR", 30);
define("E2E_MESSAGE", 100);
define("E2E_DIAGNOSTICS_MESSAGE", 110);
define("DEFAULT_TEMPLATE", "acute");
define("DEFAULT_FORMATTER", "neasden");
define("E2_NEW_FILES_RIGHTS", 0777);
define("E2_JSON_STYLE", JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
define("DEFAULT_ITEMS_PER_PAGE", 10);
define("MAX_ITEMS_PER_PAGE", 100);
define("SYSTEM_DIR", "system/");
define("SYSTEM_DEFAULTS_DIR", "system/default/");
define("SYSTEM_THEME_DIR", "system/theme/");
define("LANGUAGES_DIRNAME", "languages/");
define("LIBRARY_DIRNAME", "library/");
define("THEMES_DIRNAME", "themes/");
define("EXTRAS_DIRNAME", "extras/");
define("SCRIPTS_SUBDIR", "js/");
define("LOGS_DIRNAME", "logs/");
define("CACHES_DIRNAME", "caches/");
define("BACKUP_DIRNAME", "backup/");
define("MAIN_LOG_FILENAME", "main.log");
define("PICTURES_DIRNAME", "pictures/");
define("THUMBNAILS_DIRNAME", "pictures/thumbs/");
define("AVATARS_DIRNAME", "pictures/avatars/");
define("USERPIC_DIRNAME", "pictures/userpic/");
define("VIDEO_DIRNAME", "video/");
define("AUDIO_DIRNAME", "audio/");
define("LICENSE_FILENAME", "license.psa");
define("THUMB_WIDTH", 180);
define("THUMB_HEIGHT", 120);
define("THUMB_JPG_QUALITY", 50);
define("SCALED_IMAGE_JPG_QUALITY", 80);
define("AVATAR_SIZE", 80);
define("VIDEO_ICON_FILENAME", "images/video.svg");
define("AUDIO_ICON_FILENAME", "images/audio.svg");
define("VIDEO_ICON_WIDTH", 180);
define("VIDEO_ICON_HEIGHT", 120);
define("AUDIO_ICON_WIDTH", 120);
define("AUDIO_ICON_HEIGHT", 120);
define("ALIAS_MAX_LENGTH", 64);
define("CACHE_ALIASMAP", CACHE and true);
define("CACHE_NOTES", CACHE and true);
define("CACHE_NOTES_RELATED", CACHE and true);
define("CACHE_NOTES_COMMENTS", CACHE and true);
define("CACHE_POPULAR", CACHE and true);
define("CACHE_POPULAR_WITH_TAG", CACHE and true);
define("CACHE_RANDOM_NOTE", CACHE and true);
define("CACHE_TAGS", CACHE and true);
define("CACHE_FAVTAGS", CACHE and true);
define("CACHE_NOTES_COUNTS", CACHE and true);
define("CACHE_EDGE_TIMEINFO", CACHE and true);
define("CACHE_FRONTPAGE", CACHE and true);
define("CACHE_FRONTPAGE_FEED", CACHE and true);
define("CACHE_TAG", CACHE and true);
define("CACHE_FULLLIST", CACHE and true);
define("CACHE_DRAFTS", CACHE and true);
define("CACHE_DRAFTS_ALIAS_USE_COUNTS", CACHE and true);
define("CACHE_LASTMODIFIEDS", CACHE and true);
define("CACHE_INDEXED_FLAG", CACHE and true);
define("CACHE_FILENAME_ALIASMAP", CACHES_DIRNAME . "aliasmap.psa");
define("CACHE_FILENAMES_NOTES", CACHES_DIRNAME . "note-*.psa");
define("CACHE_FILENAMES_NOTES_RELATED", CACHES_DIRNAME . "note-*-related.psa");
define(
"CACHE_FILENAMES_NOTES_COMMENTS",
CACHES_DIRNAME . "note-*-comments.ctree.psa"
);
define(
"CACHE_FILENAMES_NOTES_COMMENTS_AUTHOR",
CACHES_DIRNAME . "note-*-comments-author.ctree.psa"
);
define("CACHE_FILENAMES_NOTES_COUNTS", CACHES_DIRNAME . "notes-count-*.txt");
define("CACHE_FILENAMES_EDGE_TIMEINFO", CACHES_DIRNAME . "*.e2time.psa");
define("CACHE_FILENAME_POPULAR", CACHES_DIRNAME . "popular.ctree.psa");
define(
"CACHE_FILENAME_POPULAR_EXPIRES",
CACHES_DIRNAME . "popular-expires.txt"
);
define("CACHE_FILENAME_RANDOM_NOTE", CACHES_DIRNAME . "random-note.psa");
define(
"CACHE_FILENAMES_POPULAR_WITH_TAG",
CACHES_DIRNAME . "popular-*.ctree.psa"
);
define(
"CACHE_FILENAMES_POPULAR_WITH_TAG_EXPIRES",
CACHES_DIRNAME . "popular-*-expires.txt"
);
define("CACHE_FILENAME_TAGS", CACHES_DIRNAME . "tags.ctree.psa");
define("CACHE_FILENAME_TAGS_FULL", CACHES_DIRNAME . "tags-full.ctree.psa");
define("CACHE_FILENAME_TAGS_AUTHOR", CACHES_DIRNAME . "tags-author.ctree.psa");
define(
"CACHE_FILENAME_TAGS_AUTHOR_FULL",
CACHES_DIRNAME . "tags-author-full.ctree.psa"
);
define("CACHE_FILENAME_FAVTAGS", CACHES_DIRNAME . "favtags.ctree.psa");
define("CACHE_FILENAME_FRONTPAGE", CACHES_DIRNAME . "frontpage.ctree.psa");
define(
"CACHE_FILENAME_FRONTPAGE_AUTHOR",
CACHES_DIRNAME . "frontpage-author.ctree.psa"
);
define("CACHE_FILENAME_FRONTPAGE_FEED", CACHES_DIRNAME . "frontpage-feed.psa");
define("CACHE_FILENAMES_TAG", CACHES_DIRNAME . "tag-*.ctree.psa");
define("CACHE_FILENAMES_TAG_AUTHOR", CACHES_DIRNAME . "tag-*-author.ctree.psa");
define("CACHE_FILENAME_FULLLIST", CACHES_DIRNAME . "notes-list.ctree.psa");
define("CACHE_FILENAME_DRAFTS", CACHES_DIRNAME . "drafts.psa");
define(
"CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS",
CACHES_DIRNAME . "drafts-auc.psa"
);
define(
"CACHE_FILENAME_LASTMODIFIEDS",
CACHES_DIRNAME . "last-modifieds-by-id.psa"
);
define("CACHE_FILENAME_INDEXED_FLAG", CACHES_DIRNAME . "indexed.flag");
define("FP_NO_ID_OR_NEW", -1);
define("FP_INSERT_ERROR", -10);
define("FP_UPDATE_ERROR", -11);
define("FP_EMPTY_FIELD", -20);
define("FP_TITLE_OR_TEXT_EMPTY", -21);
define("FP_NOT_COMMENTABLE", -30);
define("FP_COMMENT_DOUBLE_POST", -101);
define("FP_COMMENT_TOO_LONG", -102);
define("FP_COMMENT_SPAM_SUSPECT", -103);
define("NOTE_COMMENTABLE_NOW", -1);
define("NOTE_COMMENTABLE_NOW_CONDITIONALLY", -2);
define("SECONDS_IN_A_MINUTE", 60);
define("SECONDS_IN_AN_HOUR", 3600);
define("SECONDS_IN_A_DAY", 86400);
define("SECONDS_IN_A_WEEK", 604800);
define("SECONDS_IN_A_MONTH", 2592000);
define("SECONDS_IN_A_YEAR", 31536000);
function e2m_drafts($parameters)
{
global $_strings, $_config;
$draftsView = new AePageableNotesView("e2m_drafts", $parameters);
$draftsView->setPortionSize((int) $_config["drafts_per_page"]);
$draftsView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$draftsView->setWantControls(true);
$draftsView->setWantPaging(true);
$draftsView->setUseLocalHrefs(true);
if ($draftsView->isFirstPage() and CACHE_DRAFTS) {
$draftsView->setCacheFilename(USER_DIR . CACHE_FILENAME_DRAFTS);
}
$draftsView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=0 " .
"ORDER BY `LastModified` DESC"
);
$i1 = $draftsView->getNotesCTree();
if (count($i1)) {
if (Log::$a) {
__log("Thumbnails {");
}
foreach ($i1 as $k3 => $x3) {
$i1[$k3]["thumbs"] = e2_(@$x3["format-info"]["resources-detected"]);
}
if (Log::$a) {
__log("}");
}
}
$ss = $_strings["pt--drafts"];
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => $_strings["pt--drafts"],
"notes" => $i1,
"pages" => $draftsView->getPagesCTree(),
];
if (count($i1) >= 5) {
$vb["secret-link-promo"] = e2l_get_string("pm--secret-link", [
"url" => $_config["paid_features_url"],
]);
}
if ($draftsView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-drafts"];
} elseif (!$draftsView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function tb($o1)
{
global $_config;
if (Log::$a) {
__log("Drafts: find duplicate OriginalAliases...");
}
if (
CACHE_DRAFTS_ALIAS_USE_COUNTS and
is_file(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS)
) {
$p1 = @unserialize(
file_get_contents(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS)
);
}
if (CACHE_DRAFTS_ALIAS_USE_COUNTS and @is_array($p1)) {
if (Log::$a) {
__log("Drafts: retrieve cached");
}
} else {
if (Log::$a) {
__log("Drafts: assemle cacheable...");
}
$p1 = [];
sm(
"SELECT `OriginalAlias` FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=0 " .
"ORDER BY `ID`",
"get original aliases of drafts to calculate use counts"
);
$h3 = qm();
$tn = [];
foreach ($h3 as $k3 => $zy) {
@$p1[$zy["OriginalAlias"]]++;
}
if (CACHE_DRAFTS_ALIAS_USE_COUNTS) {
e3(
USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS,
serialize($p1)
);
}
}
return $p1[$o1];
}
function jb()
{
global $_strings;
$cq = "https://" . $_strings["e2--website-host"] . "/";
$vq =
"(" .
$_strings["e2--release"] .
" " .
E2_RELEASE .
", v" .
E2_VERSION .
")";
return [
"built?" => BUILT,
"installed?" => yn() !== null,
"version" => "v" . E2_VERSION,
"version-description" => $_strings["e2--vname-aegea"] . " " . $vq,
"user-folder-name" => iq(),
"cookie-prefix" => x1(),
"href" => $cq,
"about" =>
'<span title="E2 ' .
$vq .
'">' .
$_strings["e2--powered-by"] .
" " .
'<a href="' .
$cq .
'" class="nu"><u>' .
$_strings["e2--vname-aegea"] .
"</u>" .
'<span class="e2-svgi">' .
c2("aegea") .
"</span></a></span>",
];
}
function hb($bq, $type = E2E_STRANGE_ERROR)
{
global $errors, $_config;
if (!isset($errors)) {
$errors = [];
}
$yq = !ys() + 1 <= (int) $_config["show_call_stack"];
if ($bq) {
if ($bq[0] != "<") {
$bq = "<p>" . $bq . "</p>";
}
$nq = ["description" => $bq, "type" => $type];
if ($type == E2E_STRANGE_ERROR and $yq) {
$nq["backtrace"] = debug_backtrace();
}
$errors[] = $nq;
}
return true;
}
function gb($mq)
{
global $_strings;
if (count($mq) == 0) {
return false;
}
$fq = "";
$fq .=
"<p>" .
$_strings["gs--enable-write-permissions-for-the-following"] .
"</p>";
$fq .= "<ul>";
foreach ($mq as $jv) {
if ($jv == ".") {
$jv = "";
}
$fq .= "<li><tt>./" . $jv . "</tt></li>";
}
$fq .= "</ul>";
return $fq;
}
function wb($dq, $bq, $sq = false, $aq = false, $qq = [])
{
global $errors;
if (!(error_reporting() & $dq) or $dq & 8) {
return;
}
$sq = str_replace(__DIR__, "", $sq);
hb($sq . ", line " . $aq . "<br />Error " . $dq . ": " . $bq);
$errors[count($errors) - 1]["phpcode"] = $dq;
}
function ub($lq, $zq, $s2, $bf)
{
if (!(error_reporting() & $lq)) {
return;
}
throw new ErrorException($zq, 0, $lq, $s2, $bf);
}
function ib()
{
global $errors, $_config;
if (!isset($errors)) {
$errors = [];
}
@session_start();
if (is_array(@$_SESSION["errors"])) {
$e = array_merge(@$_SESSION["errors"], $errors);
} else {
$e = $errors;
}
$yq = !ys() + 1 <= (int) $_config["show_call_stack"];
if (@$_config["store_backtrace"] and $yq and $e != null) {
@e3("backtrace.psa", serialize($e));
} else {
@unlink("backtrace.psa");
}
if (isset($_SESSION["errors"])) {
unset($_SESSION["errors"]);
}
$vb = [];
$kq = false;
if (count($e) > 0) {
foreach ($e as $gb => $xq) {
if ($xq["type"] == E2E_STRANGE_ERROR) {
$xq["class"] = "serious";
$kq = true;
if ($yq) {
$xq["backtrace"] = pb($xq["backtrace"]);
}
}
if ($xq["type"] == E2E_MESSAGE) {
$xq["class"] = "info";
}
$e[$gb] = $xq;
}
$vb["each"] = $e;
if (
$kq and
@$_config["store_backtrace"] and
$yq and
is_file("debug.php")
) {
$vb["debug-link"] = "debug.php";
}
}
return $vb;
}
function ob()
{
$errors = ib();
foreach ($errors["each"] as $eq) {
echo "<p>" . $eq["description"] . "</p>";
}
die();
}
function pb($rq)
{
if (!is_array($rq)) {
return "No backtrace info";
}
$rq = array_reverse($rq);
$rq = array_splice($rq, 0, count($rq) - 1);
$e =
'<p style="background: #fea; padding: .25em .5em; line-height: 1em; overflow: hidden">';
foreach ($rq as $gb => $tq) {
($jq = @$tq["args"]) or ($jq = []);
$hq = [];
foreach ($jq as $gq) {
$hq[] = var_export($gq, true);
}
$s2 = @$tq["file"];
$s2 = str_replace($_SERVER["DOCUMENT_ROOT"], "", $s2);
$bf = @$tq["line"] ? " #" . $tq["line"] : "?";
$e .= '<div style="margin: .25em 0 .5em ' . $gb * 3 . 'em">';
$e .=
'<span style="float: right; color: #666"> ' . $s2 . $bf . "</span>";
$e .= "<tt><b>" . @$tq["function"] . " (</b>";
if (count($hq)) {
$wq = str_replace("array (\n)", "array ()", $hq);
$wq = implode(", ", $wq);
if (0) {
$wq = highlight_string("<?" . $wq . "?" . ">", true);
$wq = substr($wq, 77, -28);
}
$wq = str_replace(" ", " ", $wq);
$wq = nl2br($wq);
$e .= '<div style="margin: 0 0 0 1.12em">' . $wq . "</div>";
}
$e .= "<b>)</b> →</tt></div>";
}
$e .= "</p>";
return $e;
}
class AeException extends \Exception
{
}
class AeMySQLException extends AeException
{
}
class AeMySQLNotFoundException extends AeMySQLException
{
}
class AeMySQLTooOldException extends AeMySQLException
{
}
class AeMySQLCannotConnectException extends AeMySQLException
{
}
class AeMySQLAccessDeniedException extends AeMySQLCannotConnectException
{
}
class AeMySQLQueryException extends AeMySQLException
{
}
class AeMySQLNoDataException extends AeMySQLException
{
}
class AeMySQLNotMigrateableException extends AeMySQLException
{
}
class AeMySQLCorruptedUpdateRecordCallException extends AeMySQLException
{
}
class AeRecordNotFoundException extends AeException
{
}
class AeInstallException extends AeException
{
}
class AeInstallAlreadyInstalledException extends AeInstallException
{
}
class AeInstallDatabaseOccupiedException extends AeInstallException
{
}
class AeWritePermissionsException extends AeException
{
}
class AeNotSavedException extends AeWritePermissionsException
{
}
class AeTokenException extends AeException
{
}
class AeOlbaException extends AeException
{
}
class AeOlbaTemplateMissingException extends AeOlbaException
{
}
class AeStubException extends AeException
{
}
class AeFormException extends AeException
{
}
class AeFormInconsistentException extends AeFormException
{
}
class AeFormIncompleteException extends AeFormException
{
public $note_id = "";
function __construct($note_id)
{
$this->note_id = $note_id;
parent::__construct();
}
}
class AeFormCommentUnacceptableException extends AeFormException
{
public $comment_text = "";
function __construct($comment_text)
{
$this->comment_text = $comment_text;
parent::__construct();
}
}
class AeFormDuplicateCommentException extends AeFormCommentUnacceptableException
{
}
class AeFormCommentTooLongException extends AeFormCommentUnacceptableException
{
}
class AeFormNoteNotCommentableException extends
AeFormCommentUnacceptableException
{
}
class AeFormCommentIsSpamSuspectException extends
AeFormCommentUnacceptableException
{
}
function c3($uq, $iq = false)
{
$oq = substr(__DIR__, 0, strrpos(__DIR__, "/"));
$pq = "";
$cl = [];
foreach (array_reverse($uq->getTrace()) as $vl) {
$bl["where"] =
str_replace($oq . "/", "", $vl["file"]) . ":" . $vl["line"];
$yl = [];
foreach ($vl["args"] as $nl) {
$yl[] = htmlspecialchars(
str_replace("\n", "\n ", var_export($nl, true)),
ENT_NOQUOTES,
"UTF-8"
);
}
$ml = "";
if (count($yl)) {
$ml = "\n" . " " . implode(",\n ", $yl) . "\n";
}
$bl["call"] = $vl["function"] . " (" . $ml . ")";
$cl[] = $bl;
}
do {
if ((string) $uq->getMessage() !== "") {
$pq .= $uq->getMessage() . "\n";
}
$pq .= "\n";
$pq .=
get_class($uq) .
" in " .
str_replace($oq . "/", "", $uq->getFile()) .
":" .
$uq->getLine() .
"\n";
if ($uq->getCode()) {
$pq .= "Code: " . $uq->getCode() . "\n";
}
$fl = "";
$gb = 1;
foreach ($cl as $bf) {
$fl .= $gb++ . ". " . $bf["where"] . " " . $bf["call"] . "\n";
if (!$iq) {
$fl .= "\n";
}
}
$pq .= "\n";
} while ($uq = $uq->getPrevious());
if ($iq) {
$fl = preg_replace('/^.*?$/smu', ' $0', $fl);
$pq .= "" . "\n";
$pq .= $fl;
$pq .= "";
} else {
$pq .= $fl;
}
return $pq;
}
function v3($uq, $zq = "")
{
global $_config;
if ($_config["dev_verbose"] > (int) !ys()) {
hb("<pre>" . c3($uq) . "</pre>");
}
if ($_config["log_errors"]) {
Log::$a = true;
if (Log::$a) {
qn('error-$');
}
}
if (Log::$a) {
__log("Exception caught: " . c3($uq, true));
}
if (Log::$a) {
qn("");
}
if ((string) $zq !== "") {
if (Log::$a) {
__log($zq);
}
}
}
function b3($uq)
{
global $_config, $content;
$content["title"] = ":-(";
$content["exception-message"] = $uq->getMessage();
$dl["error"]["message"] = ":-(";
if ($_config["dev_verbose"] > (int) !ys()) {
$content["exception-string"] = c3($uq);
$dl["error"]["message"] = nl2br(c3($uq));
}
if ($_config["log_errors"]) {
Log::$a = true;
if (Log::$a) {
qn('error-$');
}
}
if (Log::$a) {
__log("Panic: " . c3($uq, true));
}
if (Log::$a) {
__log(":-(");
}
if (
array_key_exists("result", $_POST) and
$_POST["result"] == "ajaxresult"
) {
$vb = json_encode($dl);
} else {
$vb = hf("panic", true);
}
echo $vb;
die();
}
function y3($uq)
{
b3($uq);
}
function e2m_most_commented($parameters = [])
{
global $settings, $_strings, $_config;
$gn = ys();
$mostCommentedView = new AePageableNotesView(
"e2m_most_commented",
$parameters
);
$mostCommentedView->setPortionSize(
$settings["appearance"]["notes_per_page"]
);
$mostCommentedView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$mostCommentedView->setWantNewCommentsCount($gn);
$mostCommentedView->setWantReadHrefs($_config["count_reads"]);
$mostCommentedView->setWantControls($gn and !@$_config["read_only"]);
$mostCommentedView->setWantHiddenTags($gn);
AeMainMenuManager::$isMostCommentedCurrent = $mostCommentedView->isFirstPage();
AeMainMenuManager::$isMostCommentedParent = !$mostCommentedView->isFirstPage();
$sl = $_config["hot_period"];
$al = time() - n3($_config["hot_period"]);
$mostCommentedView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
df($gn) .
"AND `ID` IN ( " .
"SELECT `NoteID` FROM ( " .
"SELECT `NoteID`, COUNT(*) `CommentsCount` " .
"FROM `" .
$_config["db_table_prefix"] .
"Comments` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsVisible` = 1 " .
"AND `Stamp` > " .
$al .
" " .
"GROUP BY `NoteID` " .
"ORDER BY `CommentsCount` DESC " .
") As MostCommentedNotesIDs " .
")"
);
$vb = [
"title" => e2l_get_string("pt--most-commented", ["period" => $sl]),
"heading" => e2l_get_string("pt--most-commented", ["period" => $sl]),
"notes" => $mostCommentedView->getNotesCTree(),
"pages" => $mostCommentedView->getPagesCTree(),
];
if ($mostCommentedView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-such-notes"];
} elseif (!$mostCommentedView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function e2m_favourites($parameters = [])
{
global $settings, $_config, $_strings;
$gn = ys();
$favouritesView = new AePageableNotesView("e2m_favourites", $parameters);
$favouritesView->setPortionSize($settings["appearance"]["notes_per_page"]);
$favouritesView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$favouritesView->setWantPaging(true);
$favouritesView->setWantNewCommentsCount($gn);
$favouritesView->setWantReadHrefs($_config["count_reads"]);
$favouritesView->setWantControls($gn and !@$_config["read_only"]);
$favouritesView->setWantHiddenTags($gn);
AeMainMenuManager::$isFavouritesCurrent = $favouritesView->isFirstPage();
AeMainMenuManager::$isFavouritesParent = !$favouritesView->isFirstPage();
$favouritesView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
"AND `IsFavourite`=1 " .
df($gn) .
"ORDER BY `Stamp` DESC"
);
$ss = $_strings["pt--favourites"];
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => $_strings["pt--favourites"],
"notes" => $favouritesView->getNotesCTree(),
"pages" => $favouritesView->getPagesCTree(),
];
if ($favouritesView->isFirstPageOfEmptyView()) {
$vb["nothing"] = $_strings["gs--no-favourites"];
} elseif (!$favouritesView->isExistingPage()) {
return e2m_error404();
}
return $vb;
}
function n3($sl)
{
if ("year" == $sl) {
return SECONDS_IN_A_YEAR;
} elseif ("month" == $sl) {
return SECONDS_IN_A_MONTH;
} elseif ("week" == $sl) {
return SECONDS_IN_A_DAY * 7;
} elseif ("day" == $sl) {
return SECONDS_IN_A_DAY;
} else {
return PHP_INT_MAX;
}
}
function e2m_json($parameters = [])
{
list($ql, $in) = q3();
$ll = json_encode($ql, E2_JSON_STYLE);
x3($ll, $in, "json");
}
function e2m_rss($parameters = [])
{
list($ql, $in) = q3();
$zl = e2feeds__rss_using_jsonfeed_array_($ql);
x3($zl, $in, "rss");
}
function e2m_tag_json($parameters = [])
{
if (array_key_exists("*tag", $parameters)) {
$wb = $parameters["*tag"];
} else {
return e2m_error404();
}
list($ql, $in) = l3($wb);
$ll = json_encode($ql, E2_JSON_STYLE);
x3($ll, $in, "json");
}
function e2m_tag_rss($parameters = [])
{
if (array_key_exists("*tag", $parameters)) {
$wb = $parameters["*tag"];
} else {
return e2m_error404();
}
list($ql, $in) = l3($wb);
$zl = e2feeds__rss_using_jsonfeed_array_($ql);
x3($zl, $in, "rss");
}
function e2m_note_json($parameters = [])
{
global $settings, $_current_url;
$zy = $parameters["*note"];
if ($zy == false) {
return e2m_error404();
}
$gn = ys();
if (!(ff($zy) === "public" or $gn and $zy["IsPublished"])) {
return e2m_error404();
}
$in = $zy["Stamp"];
$kl = e2_jsonfeed_item_array_from_noterec_($zy);
$xl = [$kl];
$ql = e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl);
$ql["title"] = ev();
$ql["_rss_description"] = a3();
$ql["home_page_url"] = eq("e2m_frontpage", ["page" => 1]);
$ql["feed_url"] = $_current_url;
x3(json_encode($ql, E2_JSON_STYLE), $in, "json");
}
function e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl)
{
global $_lang, $_config, $settings;
$vb = [
"version" => "https://jsonfeed.org/version/1.1",
"title" => null,
"_rss_description" => null,
"_rss_language" => $_lang,
"_itunes_email" => "",
"_itunes_categories_xml" => "",
"_itunes_image" => "",
"_itunes_explicit" => "",
"home_page_url" => null,
"feed_url" => null,
"icon" => tv(),
"authors" => [
[
"name" => rv(),
"url" => eq("e2m_frontpage", ["page" => 1]),
"avatar" => tv(),
],
],
"items" => $xl,
"_e2_version" => E2_VERSION,
"_e2_ua_string" => E2_UA_STRING,
];
return $vb;
}
function e2_jsonfeed_item_array_from_noterec_($zy)
{
$url = eq("e2m_note", ["*note" => $zy]);
$el = n1("Y-m-d\TH:i:s", $zy["Stamp"]) . q1($zy["Stamp"], ":");
$rl =
n1("Y-m-d\TH:i:s", $zy["LastModified"]) . q1($zy["LastModified"], ":");
$tl = n1("D, d M Y H:i:s ", $zy["Stamp"]) . q1($zy["Stamp"]);
$ld = ly($zy["FormatterID"], @$zy["Text"], "full-rss");
$noteView = new AeNoteView($zy);
$u3 = $noteView->getNoteCTree();
$m3 = $u3["og-images"];
$jl = [];
foreach ($u3["tags"] as $gv) {
$jl[] = $gv["name"];
}
$v = [
"id" => (string) $zy["ID"],
"url" => $url,
"title" => ay($zy["Title"]),
"content_html" => $ld["text-final"],
"date_published" => $el,
"date_modified" => $rl,
"tags" => $jl,
];
if ($zy["IsExternal"]) {
$hl = bn($zy);
$v["url"] = $hl["href-external"];
$v["author"] = [
"name" => $hl["author"],
"url" => $hl["author-href"],
"avatar" => $hl["userpic-href"],
];
}
if (count($m3) > 0) {
$v["image"] = $m3[0];
}
$v["_date_published_rfc2822"] = $tl;
$v["_rss_guid_is_permalink"] = "false";
$v["_rss_guid"] = (string) $zy["ID"];
$v["_e2_data"] = [
"is_favourite" => (bool) $zy["IsFavourite"],
"links_required" => $ld["meta"]["links-required"],
"og_images" => $m3,
];
return $v;
}
function d3($gl, $ss, $s1)
{
global $_newsfeeds;
if (!isset($_newsfeeds)) {
$_newsfeeds = [];
}
$wl = "";
if ($gl == "rss") {
$wl = "application/rss+xml";
}
if ($gl == "json") {
$wl = "application/json";
}
$_newsfeeds[] = [
"type" => $wl,
"title" => htmlspecialchars($ss, ENT_NOQUOTES, "UTF-8"),
"href" => $s1,
];
}
function s3()
{
global $_config;
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
df() .
"ORDER BY `Stamp` DESC " .
"LIMIT " .
$_config["rss_items"],
"get recent public noterecs for RSS or JSONFeed"
);
return qm();
}
function a3()
{
global $settings;
if (!empty($settings["meta_description"])) {
$ul = strip_tags(
ay(
htmlspecialchars(
$settings["meta_description"],
ENT_NOQUOTES,
"UTF-8"
)
)
);
} elseif (!empty($settings["blog_subtitle"])) {
$ld = zy($settings["blog_subtitle"], "full");
$ul = $ld["text-final"];
$ul = mf($ul);
} else {
$ul = ev();
}
return $ul;
}
function q3()
{
global $settings, $_current_url;
$in = 0;
$xl = [];
$ql = [];
$of = USER_DIR . CACHE_FILENAME_FRONTPAGE_FEED;
if (CACHE_FRONTPAGE_FEED and is_file($of)) {
if (Log::$a) {
__log("Feed array (RSS, JSON): cached");
}
$ql = @unserialize(file_get_contents($of));
$in = filemtime($of);
} else {
if (Log::$a) {
__log("Feed array (RSS, JSON): not cached, will need to build");
}
$ff = s3();
foreach ($ff as $zy) {
$xl[] = e2_jsonfeed_item_array_from_noterec_($zy);
$in = max($in, $zy["Stamp"]);
}
$ql = e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl);
$ql["title"] = ev();
$ql["_rss_description"] = a3();
$ql["home_page_url"] = eq("e2m_frontpage", ["page" => 1]);
$ql["feed_url"] = $_current_url;
if (CACHE_FRONTPAGE_FEED) {
e3($of, serialize($ql));
}
}
return [$ql, $in];
}
function l3($wb)
{
global $_config, $_strings, $_current_url;
$in = 0;
$xl = [];
sm(
"SELECT n.* " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"INNER JOIN `" .
$_config["db_table_prefix"] .
"NotesKeywords` nk " .
"ON nk.`NoteID` = n.`ID` " .
"WHERE n.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND nk.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (nk.`KeywordID` = " .
$wb["ID"] .
") " .
"AND n.`IsPublished` = 1 " .
df(ys()) .
"ORDER BY n.`Stamp` DESC " .
"LIMIT " .
$_config["rss_items"],
"get tag noterecs for RSS or JSONFeed"
);
$ff = qm();
foreach ($ff as $zy) {
$xl[] = e2_jsonfeed_item_array_from_noterec_($zy);
$in = max($in, $zy["Stamp"]);
}
if ((string) $wb["Summary"] !== "") {
$ul = strip_tags(
ay(htmlspecialchars($wb["Summary"], ENT_NOQUOTES, "UTF-8"))
);
} elseif ((string) $wb["Description"] !== "") {
$ld = zy($wb["Description"], "full");
$ul = $ld["text-final"];
$ul = mf($ul);
} else {
$ul = a3();
}
$il = htmlspecialchars($wb["PageTitle"], ENT_COMPAT, "UTF-8");
if ((string) $il !== "") {
$ss = $il;
} else {
$ss =
ev() .
": " .
$_strings["gs--posts-tagged"] .
" " .
htmlspecialchars($wb["Keyword"], ENT_COMPAT, "UTF-8");
}
$ql = e2_jsonfeed_array_stub_from_jsonfeed_item_arrays_($xl);
$ql["title"] = $ss;
$ql["_rss_description"] = $ul;
$ql["home_page_url"] = eq("e2m_tag", ["*tag" => $wb]);
$ql["feed_url"] = $_current_url;
return [$ql, $in];
}
function e2feeds__rss_using_jsonfeed_array_($content)
{
$ol = USER_DIR . "rss/rss.tmpl.php";
if (!is_file($ol)) {
$ol = SYSTEM_DEFAULTS_DIR . "rss/rss.tmpl.php";
}
if (is_file($ol)) {
ob_start();
include $ol;
$zl = ob_get_contents();
ob_end_clean();
}
return $zl;
}
function k3($zl)
{
$pl = "";
for ($gb = 0; $gb < strlen($zl); ++$gb) {
if (in_array(ord($zl[$gb]), [10, 13]) or ord($zl[$gb]) >= 32) {
$pl .= $zl[$gb];
}
}
return $pl;
}
function x3($c4, $in, $gl)
{
global $_config;
$v4 = gmdate("r", $in);
$b4 = md5($in);
if ($gl == "rss") {
if (@$_config["dev_xml_as_text"]) {
header("Content-Type: text/plain");
} else {
header("Content-Type: application/xml; charset=utf-8");
}
} elseif ($gl == "json") {
header("Content-Type: application/json");
} else {
header("Content-Type: text/plain");
}
header("Last-modified: " . $v4);
header("Etag: " . $b4);
header("Cache-Control: public");
header("Expires: " . date("r", $in + SECONDS_IN_A_DAY));
$y4 = isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])
? stripslashes($_SERVER["HTTP_IF_MODIFIED_SINCE"])
: false;
$n4 = isset($_SERVER["HTTP_IF_NONE_MATCH"])
? stripslashes($_SERVER["HTTP_IF_NONE_MATCH"])
: false;
if (!$y4 && !$n4 or $n4 && $n4 != $b4 or $y4 && $y4 != $v4) {
if ($gl == "rss") {
$c4 = k3($c4);
}
ini_set("zlib.output_compression", 0);
echo $c4;
ini_set("zlib.output_compression", 1);
} else {
header("HTTP/1.1 304 Not Modified");
}
die();
}
define("CROP_NONE", 0);
define("CROP_SQUARE", 1);
function e3($s2, $m4)
{
@nq(dirname($s2));
if (!@file_put_contents($s2, $m4, LOCK_EX)) {
return false;
}
@chmod($s2, E2_NEW_FILES_RIGHTS);
return true;
}
function e2s_retrieve($parameters)
{
$url = base64_decode(strtr($parameters["url"], "-_", "+/"));
if (Log::$a) {
__log("Retrieve: " . $url);
}
h2($url, PROVIDE_MEDIA_NOW);
die();
}
function r3($uy, $f4, $v3)
{
$d4 = [];
if (is_array($v3)) {
$d4 = l2($v3);
}
($s4 = @unserialize($f4["Uploads"])) or ($s4 = []);
$a4 = array_diff($d4, $s4);
if (count($a4) > 0) {
u3($uy, $f4["ID"], "add", $a4);
}
return $a4;
}
function t3($q4)
{
$tv = [];
foreach (x2($q4) as $l4) {
$tv[] = $l4["src"];
}
return $tv;
}
function j3($name, $z4)
{
$name = t1($name);
if (preg_match("//u", $name)) {
$name = nl($name, false);
}
$k4 = "";
for ($gb = 0; $gb < strlen($name); $gb++) {
if ($name[$gb] == "?") {
$k4 .= "";
} elseif ($name[$gb] == " ") {
$k4 .= "-";
} elseif (ord($name[$gb]) <= 127) {
$k4 .= $name[$gb];
}
}
if ($k4 == "") {
$k4 = $z4;
}
if ($k4[0] == ".") {
$k4 = $z4 . $k4;
}
return $k4;
}
function h3($x4)
{
global $_config;
if (Log::$a) {
__log("Count references for upload <" . $x4 . ">");
}
if (is_file(USER_DIR . "new-uploads.psa")) {
$e4 = @unserialize(file_get_contents(USER_DIR . "new-uploads.psa"));
}
$r4 = "%" . str_replace("%", "#%", $x4) . "%";
sm(
"SELECT `ID`, `Text`, `FormatterID`, `Uploads` " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (`Text` LIKE '" .
$r4 .
"' ESCAPE '#' " .
"OR `Uploads` LIKE '" .
$r4 .
"' ESCAPE '#')",
"get notes where uploads may be referenced"
);
$h3 = qm();
$t4 = @unserialize($h3[0]["Uploads"]);
if (!is_array($t4)) {
foreach ($h3 as $zy) {
$ld = ly($zy["FormatterID"], @$zy["Text"], "full-rss");
$t4 = r3("note", $zy, $ld["meta"]["resources-detected"]);
}
}
sm(
"SELECT `ID`, `Description`, `Uploads` " .
"FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND (`Description` LIKE '" .
$r4 .
"' ESCAPE '#' " .
"OR `Uploads` LIKE '" .
$r4 .
"' ESCAPE '#')",
"get tags where uploads may be referenced"
);
$h3 = qm();
$j4 = @unserialize($h3[0]["Uploads"]);
if (!is_array($j4)) {
foreach ($h3 as $wb) {
$ld = zy(@$wb["Description"], "full-rss");
$j4 = r3("tag", $wb, $ld["meta"]["resources-detected"]);
}
}
if (!is_array($e4)) {
$e4 = [];
}
if (!is_array($t4)) {
$t4 = [];
}
if (!is_array($j4)) {
$j4 = [];
}
$h4 = array_merge($e4, $t4, $j4);
if (Log::$a) {
__log("References found in relevant entries: " . var_export($h4, true));
}
if (in_array($x4, $h4)) {
if (Log::$a) {
__log("Still referenced, do not delete file");
}
return true;
}
return false;
}
function g3($g4, $ey)
{
global $_config;
if ($g4 == "note" and $ey == "new") {
if (is_file(USER_DIR . "new-uploads.psa")) {
$h4 = @unserialize(file_get_contents(USER_DIR . "new-uploads.psa"));
}
} elseif ($g4 == "note") {
sm(
"SELECT `Uploads` FROM `" .
$_config["db_table_prefix"] .
"Notes` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
$h3 = qm();
$h4 = @unserialize($h3[0]["Uploads"]);
} elseif ($g4 == "tag") {
sm(
"SELECT `Uploads` FROM `" .
$_config["db_table_prefix"] .
"Keywords` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
$h3 = qm();
$h4 = @unserialize($h3[0]["Uploads"]);
}
if (!is_array($h4)) {
$h4 = [];
}
return $h4;
}
function w3($g4, $ey, $h4)
{
global $_config;
if ($g4 == "note" and $ey == "new") {
if (!@e3(USER_DIR . "new-uploads.psa", serialize($h4))) {
return false;
}
} elseif ($g4 == "note") {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Notes` " .
"SET `Uploads`='" .
serialize($h4) .
"' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
} elseif ($g4 == "tag") {
sm(
"UPDATE `" .
$_config["db_table_prefix"] .
"Keywords` " .
"SET `Uploads`='" .
serialize($h4) .
"' " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$ey
);
} else {
return false;
}
if (!is_array($h4)) {
$h4 = [];
}
return $h4;
}
function u3($g4, $ey, $action, $w4)
{
$h4 = [];
if (Log::$a) {
__log(
"Register upload: <" .
$g4 .
", " .
$ey .
", " .
$action .
", " .
$w4 .
">"
);
}
$h4 = g3($g4, $ey);
$h4 = h1($h4, $action, $w4);
return w3($g4, $ey, $h4);
}
function i3($cb, $u4, $v3)
{
($s4 = @unserialize($u4["Uploads"])) or ($s4 = []);
$i4 = l2($v3);
$h4 = h1($s4, "add", $i4);
$h4 = serialize($h4);
if ($h4 != $u4["Uploads"]) {
$u4["Uploads"] = $h4;
fm(bl(), $cb, $u4);
}
}
function e2j_file_upload($parameters = [])
{
global $_config, $_strings;
@nq($_config["path_media"] . PICTURES_DIRNAME);
@chmod(
$_config["path_media"] . PICTURES_DIRNAME,
$_config["uploaded_files_mode"]
);
@nq($_config["path_media"] . VIDEO_DIRNAME);
@chmod(
$_config["path_media"] . VIDEO_DIRNAME,
$_config["uploaded_files_mode"]
);
@nq($_config["path_media"] . AUDIO_DIRNAME);
@chmod(
$_config["path_media"] . AUDIO_DIRNAME,
$_config["uploaded_files_mode"]
);
$dl = ["success" => false];
if (count($_FILES) > 0) {
foreach ($_FILES as $s2) {
if (!$s2["error"]) {
if (Log::$a) {
__log('Ajax file upload: "' . $s2["name"] . '"');
}
$o4 = q2($s2["name"]);
$w = $o4["local-folder"];
$p4 =
(array_key_exists("overwrite", $_GET) and
is_file($w . $s2["name"]));
$cz = false;
$dl["data"]["overwrite"] = (int) $p4;
if (Log::$a) {
__log(
"Ajax file upload: Overwrite is resolved to <" .
(int) $p4 .
">"
);
}
$k4 = j3($s2["name"], $o4["default-filename"]);
if (Log::$a) {
__log("Ajax file upload: Safe name is <" . $k4 . ">");
}
if (is_file($w . $k4)) {
if (
file_get_contents($w . $k4) ==
file_get_contents($s2["tmp_name"])
) {
if (Log::$a) {
__log(
"Ajax file upload: Existing file is the same"
);
}
$cz = true;
} elseif (!$p4) {
$k4 = fd($w, $k4);
}
}
if (!$cz) {
move_uploaded_file($s2["tmp_name"], $w . $k4);
@chmod($w . $k4, $_config["uploaded_files_mode"]);
}
if (Log::$a) {
__log(
'Ajax file upload: Resource type is "' .
$o4["type"] .
'"'
);
}
if ($o4["type"] == "local-image") {
$vz = pathinfo($k4, PATHINFO_EXTENSION);
if (sd($vz, "jpg")) {
$bz = $k4;
} else {
$bz = $k4 . ".jpg";
$bz = fd(
$_config["path_media"] . PICTURES_DIRNAME,
$bz
);
}
$yz = $_config["path_media"] . PICTURES_DIRNAME . $k4;
$nz = $_config["path_media"] . PICTURES_DIRNAME . $bz;
if (Log::$a) {
__log(
'Ajax file upload: Process uploaded image "' .
$yz .
'"' .
' to possibly "' .
$nz .
'"'
);
}
$mz = false;
$nz = e2img_filename_by_processing(
$yz,
$nz,
[
$_config["fit_uploaded_images"],
$_config["fit_uploaded_images"],
],
CROP_NONE,
SCALED_IMAGE_JPG_QUALITY
);
$fz = $s2["size"];
if ($nz !== false) {
if (!sd($nz, $yz)) {
@unlink($yz);
$k4 = $bz;
$fz = stat($nz)["size"];
}
if ($p4) {
@unlink(i2($k4));
}
if (
$dz = e2img_filename_by_processing(
$nz,
i2($k4),
[THUMB_WIDTH, THUMB_HEIGHT],
CROP_NONE,
THUMB_JPG_QUALITY
)
) {
if (
u3(
$parameters["entity"],
$parameters["entity-id"],
"add",
[$k4]
)
) {
if (Log::$a) {
__log(
"Ajax file upload: thumbnail, done as " .
$dz
);
}
list($sz, $az) = e2_getimagesize($dz);
if (Log::$a) {
__log(
"Ajax file upload: image size " .
$sz .
"" .
$az
);
}
if (!$sz) {
$sz = THUMB_WIDTH / 2;
}
if (!$az) {
$az = THUMB_HEIGHT / 2;
}
list($sz, $az) = e2_fit_metrics_to_constraints(
[$sz, $az],
[THUMB_WIDTH / 2, THUMB_HEIGHT / 2]
);
$dl["success"] = true;
$dl["data"]["new-name"] = $k4;
$dl["data"]["filesize"] =
round($fz / 1024) .
" " .
$_strings["gs--kb"];
$dl["data"]["thumb"] = o3($dz);
$dl["data"]["width"] = $sz;
$dl["data"]["height"] = $az;
} else {
if (Log::$a) {
__log(
"Ajax file upload: couldnt register upload"
);
}
@unlink($w . $k4);
@unlink($dz);
$dl["error"]["message"] = _S(
"er--cannot-register-upload"
);
}
} else {
$mz = true;
}
} else {
$mz = true;
}
if ($mz) {
if (Log::$a) {
__log(
"Ajax file upload: couldnt process image for resizing"
);
}
@unlink($w . $k4);
$dl["error"]["message"] = _S(
"er--cannot-create-thumbnail"
);
}
}
if ($o4["type"] == "local-video") {
if (Log::$a) {
__log("Ajax file upload: video, done");
}
$dl["success"] = true;
$dl["data"]["new-name"] = $k4;
$dl["data"]["filesize"] =
round($s2["size"] / 1024) . " " . $_strings["gs--kb"];
$dl["data"]["thumb"] =
SYSTEM_THEME_DIR . VIDEO_ICON_FILENAME;
$dl["data"]["width"] = VIDEO_ICON_WIDTH / 2;
$dl["data"]["height"] = VIDEO_ICON_HEIGHT / 2;
u3($parameters["entity"], $parameters["entity-id"], "add", [
$k4,
]);
}
if ($o4["type"] == "local-audio") {
if (Log::$a) {
__log("Ajax file upload: audio, done");
}
$dl["success"] = true;
$dl["data"]["new-name"] = $k4;
$dl["data"]["filesize"] =
round($s2["size"] / 1024) . " " . $_strings["gs--kb"];
$dl["data"]["thumb"] =
SYSTEM_THEME_DIR . AUDIO_ICON_FILENAME;
$dl["data"]["width"] = AUDIO_ICON_WIDTH / 2;
$dl["data"]["height"] = AUDIO_ICON_HEIGHT / 2;
u3($parameters["entity"], $parameters["entity-id"], "add", [
$k4,
]);
}
} elseif (4 != $s2["error"]) {
$dl["error"]["message"] = ny($s2["error"]);
}
}
} else {
if (Log::$a) {
__log("Ajax file upload error: no files");
}
$dl["error"]["message"] = "No files were received by server";
}
$dl = json_encode($dl);
die($dl);
}
function o3($qz)
{
global $_config;
$lz = strlen($_config["path_media"]);
if ($lz and substr($qz, 0, $lz) == $_config["path_media"]) {
return substr($qz, $lz);
} else {
return AeEnv::$o . $qz;
}
}
function p3()
{
return [
"userpic.original.png",
"userpic.original.jpg",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
];
}
function cy()
{
global $_config;
foreach (p3() as $ud) {
@unlink($_config["path_media"] . USERPIC_DIRNAME . $ud);
}
}
function e2j_userpic_remove()
{
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_settings"));
}
cy();
$dl = json_encode(["success" => true]);
die($dl);
}
function e2j_userpic_upload()
{
global $_config, $_strings;
$dl = ["success" => false];
if (count($_FILES) != 1) {
if (Log::$a) {
__log("Ajax userpic upload error: no or too many files");
}
$dl["error"]["message"] =
$_strings["er--cannot-upload-no-or-too-many-files"];
$dl = json_encode($dl);
die($dl);
}
$s2 = array_pop($_FILES);
if (!$s2["error"]) {
if (Log::$a) {
__log("Ajax userpic upload: <" . $s2["name"] . ">");
}
$zz = pathinfo($s2["name"]);
$vz = strtolower($zz["extension"]);
if ($vz != "png") {
$vz = "jpg";
}
$od = "userpic.original." . $vz;
$id = $_config["path_media"] . USERPIC_DIRNAME;
cy();
move_uploaded_file($s2["tmp_name"], $id . $od);
@chmod($id . $od, $_config["uploaded_files_mode"]);
copy($id . $od, $id . "[email protected]");
e2img_filename_by_processing(
$id . "[email protected]",
$id . "[email protected]",
[$_config["max_image_width"], $_config["max_image_width"]],
CROP_NONE,
$_config["userpic_jpeg_quality"]
);
copy($id . $od, $id . "[email protected]");
$xz = e2img_filename_by_processing(
$id . "[email protected]",
$id . "[email protected]",
[$_config["max_image_width"], $_config["max_image_width"]],
CROP_SQUARE,
$_config["userpic_jpeg_quality"]
);
e2img_filename_by_processing(
$id . $od,
$id . "[email protected]",
[$_config["userpic_size"], $_config["userpic_size"]],
CROP_SQUARE,
$_config["userpic_jpeg_quality"]
);
if ($xz) {
$rz = str_replace($_config["path_media"], "", $xz);
$dl = ["success" => true, "data" => ["new-image-src" => $rz]];
} else {
$dl["error"]["message"] = _S("er--supported-only-png-jpg-gif");
}
} elseif (4 != $s2["error"]) {
$dl["error"]["message"] = ny($s2["error"]);
}
$dl = json_encode($dl);
die($dl);
}
function e2j_file_rename($parameters)
{
global $_strings;
$dl = ["success" => false];
if (
!array_key_exists("file", $_POST) or
!array_key_exists("new-name", $_POST)
) {
$dl = json_encode($dl);
die($dl);
}
$tz = $_POST["file"];
$k4 = $_POST["new-name"];
if (empty($tz) or empty($k4)) {
$dl = json_encode($dl);
die($dl);
}
if (Log::$a) {
__log('Rename "' . $tz . '" to "' . $k4 . '" {');
}
if (dd($tz) !== dd($k4)) {
$jz = pathinfo($tz);
$hz = (string) @$jz["extension"];
$k4 .= "." . $hz;
if (Log::$a) {
__log(
'Cannot change file type while renaming, will rename to "' .
$k4 .
'"'
);
}
}
$gz = q2($tz);
$wz = is_file($gz["local-folder"] . $k4);
if (
$wz and
file_get_contents($gz["local-folder"] . $tz) !==
file_get_contents($gz["local-folder"] . $k4)
) {
if (Log::$a) {
__log("Target file exists and has different content, cancelling");
}
$dl["error"]["message"] =
$_strings["er--cannot-rename-file-exists"] . ": " . $k4;
$dl = json_encode($dl);
die($dl);
}
u3($parameters["entity"], $parameters["entity-id"], "remove", $tz);
if ($wz) {
if (Log::$a) {
__log("Target file exists and is identical, will merge");
}
if (h3($tz)) {
if (Log::$a) {
__log(
"Referenced in another entity, will register under new name with this entity"
);
}
} else {
if (Log::$a) {
__log(
"Not referenced in another entity, will delete and register under new name with this entity"
);
}
$uz = [$gz["local-full-filename"]];
if ($gz["is-generating-thumbnail?"]) {
$uz[] = $gz["local-full-thumb-filename"];
}
foreach ($uz as $iz) {
if (Log::$a) {
__log("Not referenced, deleting " . $iz);
}
@unlink($iz);
}
}
u3($parameters["entity"], $parameters["entity-id"], "add", [$k4]);
} else {
if (h3($tz)) {
if (Log::$a) {
__log("Referenced in another entity, will make a copy");
}
$oz = "copy";
} else {
if (Log::$a) {
__log("Not referenced in another entity, will rename");
}
$oz = "rename";
}
if (@$oz($gz["local-full-filename"], $gz["local-folder"] . $k4)) {
u3($parameters["entity"], $parameters["entity-id"], "add", [$k4]);
if ($gz["is-generating-thumbnail?"]) {
if (Log::$a) {
__log("Will also try to copy/rename a thumbnail");
}
@$oz($gz["local-full-thumb-filename"], i2($k4));
}
} else {
if (Log::$a) {
__log("Error: couldnt " . $oz);
}
$dl = json_encode($dl);
die($dl);
}
}
$dl = ["success" => true];
$dl["data"]["new-name"] = $k4;
$dl = json_encode($dl);
if (Log::$a) {
__log("}");
}
die($dl);
}
function e2j_file_remove($parameters)
{
if (!array_key_exists("file", $_POST)) {
$dl = ["success" => false];
$dl = json_encode($dl);
die($dl);
}
$s2 = $_POST["file"];
$dl = ["success" => true];
$dl = json_encode($dl);
u3($parameters["entity"], $parameters["entity-id"], "remove", $s2);
if (!h3($s2)) {
$o4 = q2($s2);
$uz = [$o4["local-full-filename"]];
if ($o4["is-generating-thumbnail?"]) {
$uz[] = $o4["local-full-thumb-filename"];
}
foreach ($uz as $iz) {
if (Log::$a) {
__log("Not referenced, deleting " . $iz);
}
@unlink($iz);
}
}
die($dl);
}
function vy()
{
global $_config;
if (!$_config["files_total_size_limit"]) {
return false;
}
$pz = 0;
foreach (glob($_config["path_media"] . PICTURES_DIRNAME . "/*") as $s2) {
$ck = stat($s2);
$pz += $ck["size"];
}
foreach (glob($_config["path_media"] . VIDEO_DIRNAME . "/*") as $s2) {
$ck = stat($s2);
$pz += $ck["size"];
}
foreach (glob($_config["path_media"] . AUDIO_DIRNAME . "/*") as $s2) {
$ck = stat($s2);
$pz += $ck["size"];
}
$vk = $_config["files_total_size_limit"];
$bk = j1($pz, $vk);
return [$pz, $vk, $bk];
}
function by($yk)
{
$nk = true;
if (list($pz, $vk, $bk) = $yk) {
$nk = $vk - $pz > 0;
}
return $nk;
}
function yy($yk, $mk = false)
{
$fk = "";
if (list($pz, $vk, $bk) = $yk) {
$yk = [
"used" => round($pz / 1024 / 1024),
"total" => round($vk / 1024 / 1024),
"percent" => $bk,
];
if ($mk or $vk - $pz < 1024 * 1024 * 10) {
if ($pz < $vk) {
$fk = e2l_get_string("gs--used", $yk);
} else {
$fk = e2l_get_string("gs--used-all", $yk);
}
}
}
return $fk;
}
function ny($eq)
{
global $_strings;
if ($eq == UPLOAD_ERR_INI_SIZE) {
$zq = $_strings["er--cannot-upload-file-too-big"];
} elseif ($eq == UPLOAD_ERR_FORM_SIZE) {
$zq = $_strings["er--cannot-upload-file-too-big"];
} else {
$zq = e2l_get_string("er--cannot-upload", ["error" => $eq]);
}
return $zq;
}
function dy($xx)
{
$prefix = "Neasden\\";
if (BUILT) {
$ex = __DIR__ . "/library/neasden/";
} else {
$ex = __DIR__ . "/../library/neasden/";
}
$lz = strlen($prefix);
if (strncmp($prefix, $xx, $lz) !== 0) {
return;
}
$rx = substr($xx, $lz);
$s2 = $ex . str_replace("\\", "/", $rx) . ".php";
if (file_exists($s2)) {
require $s2;
}
}
function sy($tx = null)
{
global $_config, $_lang;
$jx = new Neasden\Configuration();
$jx->baseUrl = AeEnv::$o;
$jx->pathMedia = $_config["path_media"];
$jx->additionalExtensionsFolder = "user/library/neasden/";
$jx->language = $_lang;
$jx->htmlOn = true;
$jx->htmlElementsOpaque = "p ul ol li pre";
$jx->htmlElementsIgnore =
"div blockquote table tr td th thead tbody tfoot caption colgroup col";
$jx->htmlElementsSacred =
"object embed iframe head link script style code textarea";
$jx->htmlBasic = false;
$jx->htmlCodeOn = true;
$jx->htmlCodeWrap = [
'<pre class="e2-text-code"><code class="%s">',
"</code></pre>",
];
$jx->htmlCodeRequireLinks = [
"highlight/highlight.js",
"highlight/highlight.css",
];
$jx->htmlImgSrcPrefix = PICTURES_DIRNAME;
$jx->htmlImgDetect = true;
$jx->groupsOn = true;
$jx->groupsHeadingsChar = "#";
$jx->groupsHeadingsPlus = 1;
$jx->groupsQuotesChar = ">";
$jx->groupsListsChars = ["-", "*"];
$jx->groupsGenericCssClass = "e2-text-generic-object";
$jx->extensions = [
"HR",
"Block",
"AeOldList",
"Table" => ["css-class" => "e2-text-table"],
"Tweet" => ["css-class" => "e2-text-generic-object"],
];
$jx->typographyOn = true;
$jx->typographyQuotes = true;
$jx->typographyMarkup = true;
$jx->typographyAutoHref = true;
$jx->typographyNoFollowHrefs = false;
$jx->typographyUndecoratedLinksCssClass = "nu";
$jx->typographyCleanup = [
" " => "",
"«" => "",
"»" => "",
"„" => "",
"“" => "",
"”" => "",
];
if ($tx === "full" or $tx === "full-rss") {
$jx->htmlOn = true;
$jx->groupsOn = true;
$jx->typographyMarkup = true;
$jx->extensions = array_merge($jx->extensions, [
"MediaTimecodes",
"Picture" => [
"src-prefix" => PICTURES_DIRNAME,
"folder" => PICTURES_DIRNAME,
"css-class" => "e2-text-picture",
"max-width" => $_config["max_image_width"],
],
"Fotorama" => [
"src-prefix" => PICTURES_DIRNAME,
"folder" => PICTURES_DIRNAME,
"css-class" => "e2-text-picture",
"max-width" => $_config["max_image_width"],
],
"Video" => [
"src-prefix" => VIDEO_DIRNAME,
"folder" => VIDEO_DIRNAME,
"css-class" => "e2-text-video",
"max-width" => $_config["max_image_width"],
"getid3-path" =>
SYSTEM_DIR . LIBRARY_DIRNAME . "getid3/getid3.php",
],
"OnlineVideo" => [
"css-class" => "e2-text-video",
"max-width" => $_config["max_image_width"],
"ratio" => 16 / 9,
],
"Audio" => [
"src-prefix" => AUDIO_DIRNAME,
"folder" => AUDIO_DIRNAME,
"css-class" => "e2-text-audio",
"mp3info-path" =>
SYSTEM_DIR . LIBRARY_DIRNAME . "mp3info/mp3info.php",
],
]);
}
if ($tx === "simple" or $tx === "simple-rss") {
$jx->htmlOn = false;
$jx->groupsOn = true;
$jx->typographyMarkup = true;
}
if ($tx === "full-rss" or $tx === "simple-rss") {
$jx->htmlBasic = true;
}
if ($tx === "kavychki") {
$jx->htmlOn = true;
$jx->htmlCodeOn = false;
$jx->groupsOn = false;
$jx->typographyMarkup = false;
$jx->typographyAutoHref = false;
}
return $jx;
}
function ay($e1)
{
$jx = sy("kavychki");
$hx = new Neasden\Model();
$hx->addOpaqueElement($e1);
$gx = new Neasden\Renderer($jx, $hx);
return $gx->getHTML();
}
function qy($wx, $e1)
{
if ($e1 === "") {
return [];
}
if ($wx === "neasden") {
$jx = sy("full");
$ux = new Neasden\Interpreter($jx, $e1);
return $ux->getModel()->getResources();
} else {
return [];
}
}
function ly($wx, $e1, $tx)
{
if (Log::$a) {
__log(
'Format: format with formatter "' .
$wx .
'" in context "' .
$tx .
'"'
);
}
$meta = [];
$eb = "-";
if ($wx === "neasden") {
$jx = sy($tx);
$ux = new Neasden\Interpreter($jx, $e1);
$gx = new Neasden\Renderer($jx, $ux->getModel());
$e1 = $gx->getHTML();
$hx = $ux->getModel();
$eb = $hx->getFlow();
$meta = [
"links-required" => $hx->getLinks(),
"resources-detected" => $hx->getResources(),
];
}
return ["text-final" => $e1, "text-flow" => $eb, "meta" => $meta];
}
function zy($e1, $tx)
{
return ly(DEFAULT_FORMATTER, $e1, $tx);
}
function e2m_frontpage($parameters = [])
{
global $settings, $_strings, $_config;
if (Log::$a) {
__log("Frontpage {");
}
$gn = ys();
$frontpageView = new AePageableNotesView("e2m_frontpage", $parameters);
$frontpageView->setPortionSize($settings["appearance"]["notes_per_page"]);
$frontpageView->setNextPrevPageTitles(
$_strings["gs--earlier"],
$_strings["gs--later"]
);
$frontpageView->setWantPaging(true);
$frontpageView->setWantNewCommentsCount($gn);
$frontpageView->setWantReadHrefs($_config["count_reads"]);
$frontpageView->setWantControls($gn and !@$_config["read_only"]);
$frontpageView->setWantHiddenTags($gn);
$frontpageView->setWantRelatedNotes(true);
if (CACHE_FRONTPAGE and $frontpageView->isFirstPage()) {
if ($gn) {
$frontpageView->setCacheFilename(
USER_DIR . CACHE_FILENAME_FRONTPAGE_AUTHOR
);
} else {
$frontpageView->setCacheFilename(
USER_DIR . CACHE_FILENAME_FRONTPAGE
);
}
}
$frontpageView->setLimitlessSQLRequest(
"SELECT * " .
"FROM `" .
$_config["db_table_prefix"] .
"Notes` n " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `IsPublished`=1 " .
df($gn) .
"ORDER BY `Stamp` DESC"
);
$ss = ev();
if ($parameters["page"] > 1) {
$ss .= " (" . $_strings["gs--page"] . " " . $parameters["page"] . ")";
}
$vb = [
"title" => $ss,
"heading" => "",
"notes" => $frontpageView->getNotesCTree(),
"pages" => $frontpageView->getPagesCTree(),
"frontpage?" => $frontpageView->isFirstPage(),
];
if (
!$frontpageView->isExistingPage() and
!$frontpageView->isFirstPageOfEmptyView()
) {
return e2m_error404();
}
if (Log::$a) {
__log("} // Frontpage");
}
return $vb;
}
abstract class E2GIP
{
protected $gip_cookie_name = "gip";
protected $gip_token_cookie_name = "gip_access_token";
protected $gip_token = null;
abstract public function get_auth_url();
abstract public static function get_profile_url($ey, $ix);
abstract public function callback();
const PHP_VERSION_VK_FEATURE = 70100;
public static function set_session_data($yn, $vv)
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$_SESSION[$yn] = $vv;
}
public static function get_session_data($yn, $ox = false)
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION[$yn])) {
return null;
}
$vv = $_SESSION[$yn];
if ($ox) {
unset($_SESSION[$yn]);
}
return $vv;
}
public function get_config($yn)
{
$px = "gips/" . $this->type . ".json";
$ll = false;
foreach ([USER_DIR, INSTANCE_DIR, SYSTEM_DIR] as $ce) {
if (is_file($ce . $px)) {
$ll = @file_get_contents($ce . $px);
break;
}
}
if ($ll !== false) {
$vb = json_decode($ll, true, 512, JSON_BIGINT_AS_STRING)[$yn];
if ($vb) {
return $vb;
}
}
return null;
}
public function get_callback_url()
{
return eq("e2m_gip_sign_in_callback", ["provider" => $this->type]);
}
protected function get_proxy_param()
{
global $settings;
$ve = DEFAULT_LANGUAGE;
if (array_key_exists("language", $settings)) {
$ve = $settings["language"];
}
return "?language=" .
$ve .
"&type=" .
$this->type .
"&callback_url=" .
urlencode($this->get_callback_url());
}
public function get_gip_session_data()
{
global $_config;
$be = $this->gip_token
? $this->gip_token
: $_COOKIE[x1($this->gip_token_cookie_name)];
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"GIPsSessions` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `GIP` = '" .
$this->type .
"' " .
"AND `SessionToken` = '" .
lm($be) .
"' " .
"ORDER BY `ID` DESC LIMIT 1",
"get GIP session data"
);
$h3 = qm();
return $h3 ? $h3[0] : [];
}
public function is_logged_in()
{
if (
empty($_COOKIE[x1($this->gip_cookie_name)]) ||
!in_array($_COOKIE[x1($this->gip_cookie_name)], ky()) ||
$_COOKIE[x1($this->gip_cookie_name)] != $this->type ||
empty($_COOKIE[x1($this->gip_token_cookie_name)])
) {
return false;
}
$zb = $this->get_gip_session_data();
return (bool) $zb;
}
protected function save_session(
$ey,
$name,
$accessToken,
$ye = "",
$userEmail = "",
$userLink = ""
) {
$mf = time();
mm(
bl(),
"GIPsSessions",
[
"GIP" => $this->type,
"GIPAuthorID" => $ey,
"AuthorName" => $name,
"AuthorEmail" => $userEmail,
"AuthorProfileLink" => $userLink,
"SessionToken" => $accessToken,
"Stamp" => $mf,
],
"INSERT",
"ON DUPLICATE KEY UPDATE " .
'`SessionToken` = "' .
lm($accessToken) .
'", ' .
'`AuthorName` = "' .
lm($name) .
'", ' .
'`Stamp` = "' .
$mf .
'"'
);
e1($this->gip_cookie_name, $this->type);
e1($this->gip_token_cookie_name, $accessToken);
if (isset($userEmail) && !empty($userEmail)) {
e1("commenter_email", $userEmail);
}
$this->gip_token = $accessToken;
}
public static function get_logout_key()
{
if ($ne = self::get_session_data("logout_key")) {
return $ne;
}
$ne = md5(microtime());
self::set_session_data("logout_key", $ne);
return $ne;
}
public static function is_valid_logout_key($yn)
{
$me = self::get_session_data("logout_key", true);
if (empty($me) || empty($yn) || $me != $yn) {
return false;
}
return true;
}
public function logout()
{
global $_config;
e1($this->gip_cookie_name);
e1($this->gip_token_cookie_name);
sm(
"DELETE FROM `" .
$_config["db_table_prefix"] .
"GIPsSessions` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `GIP` = '" .
$this->type .
"' " .
"AND `SessionToken` = '" .
lm($_COOKIE[x1($this->gip_token_cookie_name)]) .
"'",
"logout"
);
}
public function get_avatar_size()
{
return AVATAR_SIZE;
}
public function save_avatar($ey, $fe)
{
global $_config;
if (!preg_match("/^https?\:\/\//i", $fe)) {
return;
}
$fe = str_replace("\0", "", $fe);
$ey = preg_replace("/[^a-zA-Z0-9._-]/", "", $ey);
$ey = substr($ey, 0, 64);
@nq($_config["path_media"] . AVATARS_DIRNAME);
@chmod(
$_config["path_media"] . AVATARS_DIRNAME,
$_config["uploaded_files_mode"]
);
$od =
$_config["path_media"] .
AVATARS_DIRNAME .
$this->type .
"-" .
$ey .
".jpg";
if ($de = file_get_contents($fe)) {
file_put_contents($od, $de);
}
return $od;
}
}
function e2m_gip_sign_in($zb)
{
$type = $zb["provider"];
$se = ey($type);
if (!$se) {
k1();
}
header("Location: " . $se->get_auth_url());
die();
}
function e2m_gip_sign_in_callback($zb)
{
$type = $zb["provider"];
$se = ey($type);
if (!$se) {
return e2m_error404();
}
$ae = $se->callback();
if (!$ae) {
return e2m_error404();
}
echo "<script>";
$y1 = $se->get_gip_session_data();
$qe = [
"name" => $y1["AuthorName"],
"gipIcon" => _SVG($type),
"logoutUrl" => eq("e2m_gip_sign_out", [
"provider" => E2GIP::get_logout_key(),
]),
];
echo "window.opener.oauthAuthorized(" . json_encode($qe) . ");";
echo "window.close();</script>";
die();
}
function e2m_gip_sign_out($zb)
{
$ne = $zb["provider"];
if (!E2GIP::is_valid_logout_key($ne)) {
return e2m_error404();
}
$se = jy();
if ($se) {
$se->logout();
}
k1();
}
function ky()
{
global $_config;
static $ga = null;
if ($ga !== null) {
return $ga;
}
$le = (string) @$_config["sign_in_with"];
$ze = "|twitter|facebook|vk|telegram|";
$ke = SYSTEM_DIR . "gips/";
$ga = [];
foreach (explode(",", $le) as $xe) {
$xe = trim($xe);
if ($xe == "vkontakte") {
$xe = "vk";
}
if (!strstr($ze, "|" . $xe . "|")) {
continue;
}
if (!is_file($ke . $xe . ".php")) {
continue;
}
if (in_array($xe, $ga)) {
continue;
}
if ($xe === "vk" and PHP_VERSION_ID < E2GIP::PHP_VERSION_VK_FEATURE) {
continue;
}
$ga[] = $xe;
}
return $ga;
}
function xy($type)
{
return "E2GIP" . ucfirst($type);
}
function ey($type)
{
if (!in_array($type, ky())) {
return false;
}
$ee = xy($type);
$se = new $ee();
return $se;
}
function ry($type)
{
return eq("e2m_gip_sign_in", ["provider" => $type]);
}
function ty($type = "")
{
$re = !$type ? ky() : [$type];
foreach ($re as $type) {
$se = ey($type);
if ($se && $se->is_logged_in()) {
return true;
}
}
return false;
}
function jy()
{
foreach (ky() as $type) {
$se = ey($type);
if ($se && $se->is_logged_in()) {
return $se;
}
}
return false;
}
function hy()
{
foreach (ky() as $type) {
$se = ey($type);
if ($se && $se->is_logged_in()) {
return $type;
}
}
return false;
}
function gy($type, $ey, $ix)
{
$ee = xy($type);
if (class_exists($ee)) {
return $ee::get_profile_url($ey, $ix);
} else {
return false;
}
}
function wy($type)
{
$se = ey($type);
if (!$se || !$se->is_logged_in()) {
return false;
}
return $se->get_gip_session_data();
}
function uy($xx)
{
$od =
SYSTEM_DIR .
"gips/" .
strtolower(str_replace("E2GIP", "", $xx)) .
".php";
if (is_file($od)) {
require $od;
}
}
function e2s_notify()
{
global $_config;
if (!$_config["holborn"]) {
die();
}
$te = @$_GET["src"];
if ($te == "") {
if (Log::$a) {
__log("Holborn: No src URL");
}
die();
}
$ll = file_get_contents($te);
$ll = cn($ll);
$je = json_decode($ll, true);
if (!$je) {
if (Log::$a) {
__log(
"Holborn: No meaningful info from " .
$te .
" (" .
json_last_error() .
")"
);
}
if ($he = oy($te)) {
if (Log::$a) {
__log("Holborn: Delete note with ID " . $he["ID"]);
}
gm($he["ID"]);
}
die();
}
iy($je, $te);
}
function e2m_sources($parameters)
{
global $_config;
if (!$_config["holborn"]) {
return e2m_error404();
}
$ge = $_GET["ord"];
$we = "";
if (@$ge[0] == "!") {
$ge = substr($ge, 1);
$we = " DESC";
}
if (!$ge) {
$ge = "ID";
}
$ge = "`" . lm($ge) . "`";
sm(
"SELECT S.*, " .
"REPLACE(REPLACE(REPLACE(S.`URL`, 'http://', ''), 'https://', ''), 'www.', '') AS _URLX, " .
"COUNT(N.`ID`) AS NotesCount, " .
"MAX(N.`Stamp`) AS LastNoteStamp " .
"FROM `" .
$_config["db_table_prefix"] .
"Sources` AS S, " .
" `" .
$_config["db_table_prefix"] .
"Notes` AS N " .
"WHERE S.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND N.`SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND S.`ID` = N.`SourceID`" .
"GROUP BY S.`ID` " .
"ORDER BY " .
$ge .
" " .
$we .
" " .
"LIMIT 100"
);
$h3 = qm();
foreach ($h3 as $vl) {
$ue = $vl["ID"];
if ($vl["ID"] != $vl["TrueID"]) {
$ue = "<s>" . $ue . "</s><br />=" . $vl["TrueID"];
}
$source = [
"id" => $ue,
"userpic-href" => $vl["PictureURL"],
"href" => $vl["URL"],
"href-display" => str_replace("/", "/<wbr>", $vl["URL"]),
"href-filtered" => str_replace("/", "/<wbr>", $vl["_URLX"]),
"title" => $vl["Title"],
"author" => $vl["AuthorName"],
"true?" => $vl["ID"] == $vl["TrueID"],
"whitelisted?" => (bool) $vl["IsWhiteListed"],
"trusted?" => (bool) $vl["IsTrusted"],
"notes-count" => $vl["NotesCount"],
"latest-note-time" => [$vl["LastNoteStamp"], 0],
];
if (!$vl["IsTrusted"]) {
$source["trust-url"] = eq("e2m_source_trust", [
"source" => $vl["ID"],
]);
}
if ($vl["IsTrusted"]) {
$source["premoderate-url"] = eq("e2m_source_premoderate", [
"source" => $vl["ID"],
]);
}
$source["ban-url"] = eq("e2m_source_ban", ["source" => $vl["ID"]]);
$source["forget-url"] = eq("e2m_source_forget", [
"source" => $vl["ID"],
]);
$ie[] = $source;
}
$vb = ["title" => "Sources", "heading" => "Sources"];
if (count($ie)) {
$vb["sources"] = $ie;
} else {
$vb["nothing"] = "No sources";
}
return $vb;
}
function e2m_source_trust($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Sources " .
"SET `IsWhitelisted`=1, `IsTrusted`=1 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"trust source"
);
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Notes " .
"SET `IsPublished`=1 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`=" .
$oe,
"publish all notes from the just trusted source"
);
cb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
@unlink(USER_DIR . CACHE_FILENAME_INDEXED_FLAG);
z1();
}
function e2m_source_premoderate($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Sources " .
"SET `IsTrusted`=0 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"distrust source, set to premoderation"
);
cb();
z1();
}
function e2m_source_ban($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"UPDATE " .
$_config["db_table_prefix"] .
"Sources " .
"SET `IsWhiteListed`=0, `IsTrusted`=0 " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"ban source"
);
sm(
"DELETE FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`=" .
$oe,
"delete all notes from the just banned source"
);
cb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
z1();
}
function e2m_source_forget($parameters)
{
global $_config;
$oe = $parameters["source"];
sm(
"DELETE FROM " .
$_config["db_table_prefix"] .
"Sources " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`=" .
$oe,
"forget source"
);
sm(
"DELETE FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`=" .
$oe,
"delete all notes from the just forgotten source"
);
cb();
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS);
@unlink(USER_DIR . CACHE_FILENAME_DRAFTS_ALIAS_USE_COUNTS);
z1();
}
function iy($pe, $te)
{
global $_config;
if (!array_key_exists("author", $pe)) {
$pe["author"] = $pe["authors"][0];
}
$c6 = vn([
"author" => $pe["author"]["name"],
"title" => $pe["title"],
"href" => $pe["author"]["url"],
"userpic-href" => $pe["author"]["avatar"],
]);
if (!$c6["IsWhiteListed"]) {
return;
}
if (
preg_match("/\+(\d\d)\:(\d\d)/", $pe["items"][0]["date_published"], $v6)
) {
$t3 = $v6[1] * SECONDS_IN_AN_HOUR + $v6[2] * SECONDS_IN_A_MINUTE;
}
($b6 = @$pe["items"][0]["_e2_data"]) or ($b6 = []);
$b6 = json_encode($b6);
$y6 = $c6["IsTrusted"];
$databaseConfiguration = bl();
$zy = [
"Title" => $pe["items"][0]["title"],
"Text" => $pe["items"][0]["content_html"],
"FormatterID" => "raw",
"OriginalAlias" => "",
"Uploads" => "",
"Stamp" => strtotime($pe["items"][0]["date_published"]),
"Offset" => (int) $t3,
"IsDST" => 0,
"LastModified" => strtotime($pe["items"][0]["date_modified"]),
"IsCommentable" => 0,
"IsPublished" => $y6,
"IsExternal" => 1,
"SourceID" => $c6["ID"],
"SourceNoteID" => $pe["items"][0]["id"],
"SourceNoteURL" => $pe["items"][0]["url"],
"SourceNoteJSONURL" => $te,
"SourceNoteData" => $b6,
];
$note_id = $pe["items"][0]["id"];
if ($he = py($c6["ID"], $note_id)) {
$zy["ID"] = $he["ID"];
fm($databaseConfiguration, "Notes", $zy);
} else {
$zy = mm($databaseConfiguration, "Notes", $zy);
}
if ($y6) {
if (xd($zy)) {
$zy["IsIndexed"] = "1";
fm(bl(), "Notes", $zy);
}
}
$n6 = @$pe["items"][0]["tags"];
if (is_array($n6)) {
ya($databaseConfiguration, $zy["ID"], $n6);
}
e2_drop_caches_for_note_($zy["ID"], $y6);
if ($_config["backup_automatically"]) {
zm();
}
}
function oy($te)
{
global $_config;
sm(
"SELECT `ID` FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceNoteJSONURL`='" .
lm($te) .
"' " .
"LIMIT 1",
"get note ID by source JSON URL"
);
$h3 = qm();
return $h3[0];
}
function py($oe, $m6)
{
global $_config;
sm(
"SELECT `ID` FROM " .
$_config["db_table_prefix"] .
"Notes " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `SourceID`= '" .
$oe .
"' " .
"AND `SourceNoteID`= '" .
$m6 .
"' " .
"LIMIT 1",
"get note ID by source ID and source note ID"
);
$h3 = qm();
return $h3[0];
}
function cn($ll)
{
for ($gb = 0; $gb <= 31; ++$gb) {
$ll = str_replace(chr($gb), "", $ll);
}
$ll = str_replace(chr(127), "", $ll);
if (0 === strpos(bin2hex($ll), "efbbbf")) {
$ll = substr($ll, 3);
}
return $ll;
}
function vn($f6)
{
global $_config;
$d6 = false;
sm(
"SELECT * FROM " .
$_config["db_table_prefix"] .
"Sources " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `URL`= '" .
$f6["href"] .
"' " .
"LIMIT 1",
"get source record by the URL from blog info"
);
$h3 = qm();
if (count($h3)) {
$d6 = $h3[0];
if ($d6["ID"] != $d6["TrueID"]) {
sm(
"SELECT * FROM " .
$_config["db_table_prefix"] .
"Sources " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID`= '" .
$d6["TrueID"] .
"' " .
"LIMIT 1",
"get true source record by using the TrueID of just found record"
);
$h3 = qm();
if (count($h3)) {
$d6 = $h3[0];
}
}
}
$c6 = [
"Title" => $f6["title"],
"AuthorName" => $f6["author"],
"PictureURL" => $f6["userpic-href"],
];
if ($d6 !== false) {
if (
$d6["Title"] !== $f6["title"] or
$d6["AuthorName"] !== $f6["author"] or
$d6["PictureURL"] !== $f6["userpic-href"]
) {
$c6["ID"] = $d6["ID"];
fm(bl(), "Sources", $c6);
}
return $d6;
} else {
$c6["URL"] = $f6["href"];
$c6["IsWhiteListed"] = 1;
$c6["IsTrusted"] = 0;
$c6 = mm(bl(), "Sources", $c6);
$c6["TrueID"] = $c6["ID"];
fm(bl(), "Sources", $c6);
return $c6;
}
}
function bn($zy)
{
global $_config;
$ma = [];
if (@$zy["IsExternal"]) {
if (array_key_exists("SourceID", $zy)) {
sm(
"SELECT * FROM `" .
$_config["db_table_prefix"] .
"Sources` " .
"WHERE `SubsetID`=" .
$_config["db_table_subset"] .
" " .
"AND `ID` = '" .
$zy["SourceID"] .
"'",
"get source by id"
);
$kb = qm();
$ma["source"] = $kb[0]["Title"];
$ma["source-id"] = (int) $zy["SourceID"];
$ma["source-true-id"] = (int) $kb[0]["TrueID"];
$ma["source-whitelisted?"] = (bool) $kb[0]["IsWhiteListed"];
$ma["source-trusted?"] = (bool) $kb[0]["IsTrusted"];
if (!$kb[0]["IsTrusted"]) {
$ma["source-trust-url"] = eq("e2m_source_trust", [
"source" => $zy["SourceID"],
]);
}
if ($kb[0]["IsTrusted"]) {
$ma["source-premoderate-url"] = eq("e2m_source_premoderate", [
"source" => $zy["SourceID"],
]);
}
$ma["source-ban-url"] = eq("e2m_source_ban", [
"source" => $zy["SourceID"],
]);
$ma["source-forget-url"] = eq("e2m_source_forget", [
"source" => $zy["SourceID"],
]);
$ma["author"] = $kb[0]["AuthorName"];
$ma["author-href"] = $kb[0]["URL"];
$ma["userpic-href"] = $kb[0]["PictureURL"];
}
if (
array_key_exists("SourceNoteURL", $zy) and
@$zy["SourceNoteURL"] != ""
) {
$ma["href-external"] = $zy["SourceNoteURL"];
}
}
return $ma;
}
function e2img_filename_by_processing($s6, $a6, $q6, $l6, $z6)
{
global $_config;
if (Log::$a) {
__log('Process image: "' . $s6 . '" -> "' . $a6 . '"');
}
if (!is_file($s6)) {
return false;
}
$k6 = stat($s6)["size"];
if (!vd($s6)) {
if (Log::$a) {
__log("Process image: SVG, no processing");
}
return $s6;
}
if (is_file($a6) and filesize($a6) > 0 and !sd($s6, $a6)) {
if (Log::$a) {
__log("Process image: Already exists");
}
return $a6;
}
$x6 = pathinfo($a6);
if (!@nq($x6["dirname"])) {
if (Log::$a) {
__log(
"Process image: Cant create directory <" .
$x6["dirname"] .
">"
);
}
return false;
}
if (Log::$a) {
__log("Process image: Detecting image type");
}
$type = e2img__type_of_file($s6);
if (!$type) {
return false;
}
$e6 = "imagecreatefrom" . $type;
if (!function_exists($e6)) {
if (Log::$a) {
__log("Process image: Function does not exist (" . $e6 . ")");
}
return false;
}
if (Log::$a) {
__log("Process image: Opening original image (" . $e6 . ")");
}
$r6 = call_user_func($e6, $s6);
if (!$r6) {
return false;
}
if ($t6 = e2img__orientation_of_file($s6)) {
if (Log::$a) {
__log("Process image: Needs orientation fix");
}
$r6 = e2img__res_rotate($r6, -$t6);
}
$j6 = [imagesx($r6), imagesy($r6)];
$h6 = $j6;
$g6 = [0, 0, 0, 0];
if ($l6 == CROP_SQUARE) {
if (Log::$a) {
__log("Process image: Needs crop");
}
list($h6, $g6) = e2img__crop_metrics_to_square($h6);
}
$h6 = e2_fit_metrics_to_constraints($h6, $q6);
if ($t6 === 0 and $h6 === $j6) {
if (Log::$a) {
__log("Process image: No changes necessary, leaving original");
}
return $s6;
}
if (Log::$a) {
__log(var_export($h6, true));
}
if (Log::$a) {
__log(var_export($g6, true));
}
$w6 = e2img__create_copy_resampled($r6, $h6, $g6, $type);
imagejpeg($w6, $a6, $z6);
if (!is_file($a6)) {
if (Log::$a) {
__log("Process image: File not created by imagejpeg");
}
return false;
}
if ($a6 !== $s6) {
if ($t6 === 0) {
$u6 = stat($a6)["size"];
if ($u6 >= $k6) {
if (Log::$a) {
__log(
"Process image: Conversion to JPEG made file bigger, back up"
);
}
@unlink($a6);
$a6 = $s6;
}
}
}
@chmod($a6, $_config["uploaded_files_mode"]);
if (Log::$a) {
__log("Process image: Done");
}
return $a6;
}
function e2img__create_copy_resampled($r6, $h6, $g6, $type)
{
list($i6, $o6) = $h6;
list($p6, $cr, $vr, $br) = $g6;
$w6 = imagecreatetruecolor($i6, $o6);
if ($type === "png") {
imagefill($w6, 0, 0, imagecolorallocate($w6, 255, 255, 255));
imagealphablending($w6, true);
}
$yr = imagesx($r6);
$nr = imagesy($r6);
imagecopyresampled(
$w6,
$r6,
0,
0,
0 + $p6,
0 + $cr,
$i6,
$o6,
$yr - $vr,
$nr - $br
);
imageinterlace($w6, 1);
return $w6;
}
function e2img__type_of_file($od)
{
$mr = @getimagesize($od);
if (!$mr) {
return false;
}
if (defined("IMAGETYPE_GIF") and $mr[2] == IMAGETYPE_GIF) {
return "gif";
}
if (defined("IMAGETYPE_JPEG") and $mr[2] == IMAGETYPE_JPEG) {
return "jpeg";
}
if (defined("IMAGETYPE_PNG") and $mr[2] == IMAGETYPE_PNG) {
return "png";
}
if (defined("IMAGETYPE_WEBP") and $mr[2] == IMAGETYPE_WEBP) {
return "webp";
}
return false;
}
function e2img__orientation_of_file($od)
{
if (!function_exists("exif_read_data")) {
return 0;
}
if (($fr = @exif_read_data($od)) === false) {
return 0;
}
if (@$fr["Orientation"] == 3) {
return -180;
}
if (@$fr["Orientation"] == 6) {
return -270;
}
if (@$fr["Orientation"] == 8) {
return -90;
}
return 0;
}
function e2img__res_rotate($dr, $t6)
{
$sr = imagerotate($dr, $t6, 0);
if ($sr !== false) {
imagedestroy($dr);
$dr = $sr;
}
return $dr;
}
function e2_fit_metrics_to_constraints($ar, $q6)
{
if ($q6 === false) {
$q6 = [0, 0];
}
list($sz, $az) = $ar;
list($qr, $lr) = $q6;
$zr = [1];
if ($qr) {
$zr[] = $qr / $sz;
}
if ($lr) {
$zr[] = $lr / $az;
}
$kr = min($zr);
if ($kr < 1) {
$sz = (int) round($sz * $kr);
$az = (int) round($az * $kr);
}
return [$sz, $az];
}
function e2_getimagesize_jpeg($od)
{
$xr = @fopen($od, "r");
if ($xr === false) {
throw new \RuntimeException(error_get_last()["message"]);
}
try {
if (!flock($xr, LOCK_SH)) {
throw new \RuntimeException("Cannot lock the file: " . $od);
}
$m2 = fread($xr, 2);
if ($m2 !== "\xFF\xD8") {
throw new \RuntimeException("Unknown format: " . $od);
}
for (;;) {
$er = @unpack("H4segment/nlen", fread($xr, 4));
if ($er === false) {
throw new \RuntimeException("Unknown format: " . $od);
}
$lz = $er["len"];
$rr = $er["segment"];
if (preg_match("/^ffc[0-3]/", $rr)) {
$tr = @unpack("Cbits/nheight/nwidth", fread($xr, $lz - 2));
if ($tr === false) {
throw new \RuntimeException("Unknown format: " . $od);
}
return [$tr["width"], $tr["height"]];
}
if (fseek($xr, $lz - 2, SEEK_CUR) !== 0) {
throw new \RuntimeException(
"Cannot find start of frame: " . $od
);
}
}
} finally {
fclose($xr);
}
}
function e2_getimagesize($od)
{
$sz = $az = 0;
if (p2($od)) {
try {
list($sz, $az) = e2_getimagesize_jpeg($od);
} catch (\Exception $e) {
list($sz, $az) = getimagesize($od);
}
} elseif (vd($od)) {
list($sz, $az) = getimagesize($od);
} elseif (yd($od)) {
try {
require_once SYSTEM_DIR . LIBRARY_DIRNAME . "getid3/getid3.php";
$mr = new getid3();
$mr = $mr->analyze($od);
$sz = $mr["video"]["resolution_x"];
$az = $mr["video"]["resolution_y"];
} catch (\Exception $e) {
}
} elseif (bd($od)) {
if (function_exists("simplexml_load_string")) {
$jr = simplexml_load_string(file_get_contents($od));
if ($jr) {
$hr = $jr->attributes();
list($sz, $az) = [(string) $hr->width, (string) $hr->height];
}
}
}
if (substr($od, strrpos($od, ".") - 3, 3) == "@2x") {
$sz = (int) floor($sz / 2);
$az = (int) floor($az / 2);
}
$gr = round($az > 0 ? $sz / $az : 1, 2);
$wr = round($sz > 0 ? $az / $sz : 1, 2);
return [$sz, $az, $gr, $wr];
}
function e2img__crop_metrics_to_square($ar)
{
$ur = $ir = $or_ = $pr = 0;
list($sz, $az) = $ar;
if ($sz > $az) {
$or_ = $sz - $az;
$ur = floor($or_ / 2);
$az = $sz;
} elseif ($sz < $az) {
$pr = $az - $sz;
$ir = floor($or_ / 2);
$sz = $az;
}
$g6 = [$ur, $ir, $or_, $pr];
$ct = [$sz, $az];
return [$ct, $g6];
}
function e2m_install()
{
global $_strings, $_config;
kf(DEFAULT_TEMPLATE);
$vb = [];
if (Log::$a) {
__log("Installer: not installed, present user with form");
}
$vt["server"] = @$_COOKIE[x1("install_db_server")];
$vt["user_name"] = @$_COOKIE[x1("install_db_user_name")];
$vt["passw"] = ks(@$_COOKIE[x1("install_db_passw")]);
$vt["name"] = @$_COOKIE[x1("install_db_name")];
$vb = [
"title" => $_strings["pt--install"],
"heading" => $_strings["pt--install"],
"form-install" => [
"form-action" => eq("e2s_install"),
"form-check-db-config-action" => eq("e2j_check_db_config"),
"form-list-databases-action" => eq("e2j_list_databases"),
"submit-text" => $_strings["fb--begin"],
"db-server" => htmlspecialchars(
@$vt["server"] ? $vt["server"] : "localhost"
),
"db-user" => htmlspecialchars(
@$vt["user_name"] ? $vt["user_name"] : "root"
),
"db-password" => "",
"db-database" => htmlspecialchars((string) @$vt["name"]),
],
];
return $vb;
}
function yn()
{
static $se = null;
if ($se === null) {
($se = @unserialize(
@file_get_contents(INSTANCE_DIR . "instance.psa")
)) or ($se = null);
}
return $se;
}
function nn($bt)
{
static $se = null;
$se = yn();
$se["version"] = $bt;
if (e3(INSTANCE_DIR . "instance.psa", serialize($se))) {
return $se;
} else {
die("Cannot instantiate v" . $bt . ": probably permission denied");
}
}
function e2s_instantiate($parameters)
{
global $_strings;
if (yn() !== null) {
die('Remove the file "' . INSTANCE_DIR . 'instance.psa" first');
} else {
if (is_numeric($parameters["version"])) {
if (nn($parameters["version"])) {
hb(
$_strings["gs--instantiated-version"] .
" v" .
$parameters["version"],
E2E_MESSAGE
);
z1(eq("e2m_frontpage", ["page" => 1]));
}
}
}
die("Could not create instance of engine");
}
function e2_install($databaseConfiguration, $zb)
{
global $_strings, $_config, $settings;
if (yn() !== null and bl() !== null and vs()) {
throw new AeInstallAlreadyInstalledException(
"Instance already created and db params set"
);
}
$databaseConfiguration->setPrefix($_config["db_table_prefix"]);
$databaseConfiguration->setSubset($_config["db_table_subset"]);
if (array_key_exists("db_plain_password", $zb)) {
$databaseConfiguration->password = zs($zb["db_plain_password"]);
}
if ($_config["log_installs"]) {
Log::$a = true;
if (Log::$a) {
qn('install-$');
}
}
if (Log::$a) {
__log("Installer: force directories");
}
AeFileManager::forceAllDirectories();
if (Log::$a) {
__log("Installer: write password hash");
}
if (
!@e3(USER_DIR . "password-hash.psa", serialize(sha1($zb["password"])))
) {
throw new AeNotSavedException();
}
$settings["db"] = $databaseConfiguration->getDatabaseParamsArray();
$settings["template"] = DEFAULT_TEMPLATE;
$settings["language"] = DEFAULT_LANGUAGE;
dm($databaseConfiguration, "check database during installation");
$yt = pn($databaseConfiguration);
$nt = false;
if ($yt["occupied"]) {
if ($yt["migrateable"] and $zb["allow_migration"]) {
$nt = true;
if (Log::$a) {
__log("Installer: data exists and migrateable");
}
} else {
if (Log::$a) {
__log("Installer: incomplete data in the database");
}
throw new AeInstallDatabaseOccupiedException(
"Database already has some data"
);
}
}
if ($nt) {
if (Log::$a) {
__log("Installer: no need to create tables, will migrate");
}
try {
wn($databaseConfiguration);
} catch (AeMySQLException $e) {
v3($e, "Could not migrate");
hb($_strings["er--double-check-db-params"]);
}
wd($databaseConfiguration);
} else {
if (Log::$a) {
__log("Installer: create tables");
}
foreach (AeModel::unprefixedCoreTablesNames() as $cb) {
nm($databaseConfiguration, $cb);
}
}
if (Log::$a) {
__log("Installer: write settings");
}
if (
!@e3(USER_DIR . "settings.json", json_encode($settings, E2_JSON_STYLE))
) {
throw new AeNotSavedException();
}
if (Log::$a) {
__log("Installer: search index");
}
$mt = jd(bl());
try {
$mt->erase();
} catch (\S2\Rose\Exception\RuntimeException $e) {
if (Log::$a) {
__log("Installer: Rose not available");
}
}
e2_drop_all_kinds_of_cache();
ld(USER_DIR);
rm($databaseConfiguration);
if (Log::$a) {
__log("Installer: instantiate");
}
nn(E2_VERSION);
if (Log::$a) {
__log("Installer: complete");
}
}
function e2s_install()
{
global $_strings, $_db, $_config;
if (yn() !== null and bl() !== null and vs()) {
z1();
}
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$_POST,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
foreach ($databaseConfiguration->getDatabaseParamsArray() as $k3 => $x3) {
e1("install_db_" . $k3, $x3);
}
if (
!array_key_exists("password", $_POST) or
trim($_POST["password"]) == ""
) {
hb($_strings["er--no-password-entered"], E2E_USER_ERROR);
z1(eq("e2m_frontpage"));
}
$ft = trim($_POST["password"]);
@session_start();
$dt = false;
try {
e2_install($databaseConfiguration, [
"allow_migration" => true,
"password" => $ft,
]);
$dt = true;
} catch (AeMySQLCannotConnectException $e) {
hb(
$_strings["er--cannot-connect-to-db"] .
":<br />" .
mysqli_connect_error() .
" (" .
mysqli_connect_errno() .
")"
);
} catch (AeMySQLTooOldException $e) {
hb(
e2l_get_string("er--dbs-version-too-old", [
"dbs" => $_db["software"],
"v1" => $_db["version"],
"v2" => $_db["version-minimum"],
])
);
} catch (AeMySQLException $e) {
hb(
$_strings["er--cannot-find-db"] . " " . $databaseConfiguration->name
);
} catch (AeInstallDatabaseOccupiedException $e) {
hb($_strings["er--db-data-incomplete-install"]);
} catch (AeNotSavedException $e) {
hb($_strings["er--settings-not-saved"], E2E_PERMISSIONS_ERROR);
} catch (AeInstallException $e) {
}
mn();
if (!$dt) {
z1(eq("e2m_frontpage", ["page" => 1]));
}
$st["sessions"] = [
[
"stamp" => time(),
"remote_ip" => pd(),
"key_hash" => bs(true),
"ua" => $_SERVER["HTTP_USER_AGENT"],
],
];
if (!ms($st)) {
hb($_strings["er--cannot-write-auth-data"], E2E_PERMISSIONS_ERROR);
}
vv(eq("e2s_bsi_step", []));
z1();
}
function mn()
{
global $_config;
if (strpos($_SERVER["SERVER_SOFTWARE"], "Apache") !== 0) {
return;
}
if (Log::$a) {
__log("Running on Apache");
}
$at = SYSTEM_DEFAULTS_DIR . "default.htaccess";
$qt = false;
if (!is_file($at)) {
echo "File not found: " .
$at .
". Please use the full Aegea installation package.";
die();
}
$lt = file_get_contents($at);
foreach (
["custom_htaccess_directives", "custom_htaccess_rewrites"]
as $zt
) {
if ((string) @$_config[$zt] !== "") {
$lt = str_replace(
"##" . $zt . "##\r\n",
(string) @$_config[$zt],
$lt
);
} else {
$lt = str_replace("\r\n##" . $zt . "##\r\n", "", $lt);
}
}
if (is_file(".htaccess")) {
if (Log::$a) {
__log("There is an .htaccess file in the installation directory");
}
$kt = file_get_contents(".htaccess");
if ($kt != $lt) {
$qt = true;
$xt = $et = ".htaccess.old";
$rt = 1;
while (is_file($et)) {
$et = $xt . "." . $rt++;
}
if (Log::$a) {
__log("Existing .htaccess wrong, backing up as <" . $et . ">");
}
if (!@rename(".htaccess", $et)) {
if (Log::$a) {
__log("Installer: fuck");
}
echo 'Looks like you are using Apache and have put an incorrect ".htaccess" file in the installation directory. Additionally, the installer was not able to back up your existing ".htaccess" file in order to replace it with the correct one. Please use the full E2 installation package and grant write access on the installation target directory, all the files and subdirectories.';
die();
}
}
} else {
$qt = true;
}
if ($qt) {
if (Log::$a) {
__log("Writing a correct .htaccess file");
}
if (!@file_put_contents(".htaccess", $lt)) {
if (Log::$a) {
__log("Fuck");
}
echo 'The installer was not able to create a correct ".htaccess" file. Please grant write access on the installation target directory.';
die();
}
@chmod(".htaccess", E2_NEW_FILES_RIGHTS);
}
}
function e2j_check_db_config()
{
global $_db, $_strings, $_config;
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$_POST,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
$dl = [
"success" => true,
"data" => [
"message" => "",
"db-responding" => false,
"db-connected" => false,
"db-found" => false,
"db-compatible" => false,
"db-occupied" => false,
"db-migrateable" => false,
],
];
try {
dm($databaseConfiguration, "connect to check DB config (try 1)");
} catch (AeMySQLAccessDeniedException $e) {
$dl["data"]["db-responding"] = true;
$dl = json_encode($dl);
die($dl);
} catch (AeMySQLCannotConnectException $e) {
$dl = json_encode($dl);
die($dl);
} catch (AeMySQLTooOldException $e) {
$dl["data"]["db-responding"] = true;
$dl["data"]["db-connected"] = true;
$dl["data"]["message"] = e2l_get_string("er--dbs-version-too-old", [
"dbs" => $_db["software"],
"v1" => $_db["version"],
"v2" => $_db["version-minimum"],
]);
$dl = json_encode($dl);
die($dl);
} catch (AeMySQLNotFoundException $e) {
$dl["data"]["db-responding"] = true;
$dl["data"]["db-connected"] = true;
if ($databaseConfiguration->name) {
$dl = json_encode($dl);
die($dl);
} else {
$tt = vm($databaseConfiguration);
if (count($tt) > 0) {
$dl["data"]["db-found"] = true;
$databaseConfiguration->name = $tt[0];
} else {
$dl = json_encode($dl);
die($dl);
}
}
}
$dl["data"]["db-responding"] = true;
$dl["data"]["db-connected"] = true;
$dl["data"]["db-found"] = true;
$dl["data"]["db-compatible"] = true;
try {
dm($databaseConfiguration, "connect to check DB config (try 2)");
} catch (AeMySQLException $e) {
$dl = json_encode($dl);
die($dl);
}
$dl["data"]["db-good"] = true;
$yt = pn($databaseConfiguration);
if ($yt["occupied"]) {
if ($yt["migrateable"]) {
$dl["data"]["message"] = $_strings["gs--data-exists"];
} else {
$dl["data"]["db-good"] = false;
$dl["data"]["message"] =
$_strings["er--db-data-incomplete-install"];
}
}
$dl = json_encode($dl);
die($dl);
}
function e2j_list_databases()
{
global $_config;
$databaseConfiguration = ws(
USER_DIR . BACKUP_DIRNAME,
$_POST,
$_config["db_table_prefix"],
$_config["db_table_subset"]
);
$jt = [];
$dl = ["success" => true, "data" => ["databases-list" => []]];
try {
$jt = vm($databaseConfiguration);
$dl["data"]["databases-list"] = $jt;
} catch (AeMySQLException $e) {
}
$dl = json_encode($dl);
die($dl);
}
if (substr((string) @$_SERVER["HTTP_ACCEPT_LANGUAGE"], 0, 2) == "ru") {
define("DEFAULT_LANGUAGE", "ru");
} else {
define("DEFAULT_LANGUAGE", "en");
}
function e2l_get_string($ht, $zb)
{
global $_strings;
$name = $_strings[$ht];
if (preg_match_all('/\$\[(.+?)\]/u', $name, $v6, PREG_SET_ORDER)) {
foreach ($v6 as $gt) {
$wt = $gt[1];
$wx = "";
if (strstr($wt, ".")) {
list($wt, $wx) = explode(".", $wt, 2);
}
if (array_key_exists($wt, $zb)) {
if ($wx) {
$name = str_replace(
$gt[0],
e2l__format_value($wx, $zb[$wt], $ht),
$name
);
} else {
$name = str_replace($gt[0], $zb[$wt], $name);
}
}
}
}
return $name;
}
function e2l__format_value($wx, $vv, $ht)
{
@list($wx, $ut) = explode(".", $wx, 2);
$it = "e2lstr_" . $wx;
if (function_exists($it)) {
return call_user_func($it, $vv, $ut, $ht);
} else {
return $vv;
}
return $vv;
}
function fn_()
{
global $_lang, $settings;
if (
array_key_exists("language", $settings) and
is_file(
$ot =
SYSTEM_DIR . LANGUAGES_DIRNAME . $settings["language"] . ".php"
)
) {
$_lang = $settings["language"];
include $ot;
} elseif (
is_file(
$ot = SYSTEM_DIR . LANGUAGES_DIRNAME . DEFAULT_LANGUAGE . ".php"
)
) {
$_lang = DEFAULT_LANGUAGE;
include $ot;
} else {
die("Language file missing: " . $ot);
}
return e2l_load_strings();
}
class Log
{
public static $a = false;
public static $m5 = false;
}
function an()
{
global $_config;
$f5 = INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME;
if (
$_config["write_log"] and
($_config["write_log_create"] or is_file($f5))
) {
Log::$a = true;
Log::$m5 = true;
} else {
Log::$a = false;
Log::$m5 = false;
}
if (!Log::$a) {
return;
}
@nq(INSTANCE_DIR . LOGS_DIRNAME);
if ($_config["write_log_reset"]) {
@file_put_contents($f5, "");
@chmod($f5, E2_NEW_FILES_RIGHTS);
}
if (@$_config["write_log_limit"] and is_file($f5)) {
$cs = @stat($f5);
$cs = $cs["size"];
if ($cs > $_config["write_log_limit"]) {
@rename($f5, $f5 . ".bak");
@chmod($f5 . ".bak", E2_NEW_FILES_RIGHTS);
@file_put_contents($f5, "");
}
}
__log(
""
);
}
function qn($d5 = false)
{
static $s5 = false;
if ($d5 === false) {
return $s5;
}
if ($d5 === "") {
return $s5 = false;
}
$od = str_replace('$', gmdate('Y-m-d-\a\t-H-i-s'), $d5);
return $s5 = $od;
}
function __log($e1)
{
static $q5;
global $_stopwatch;
$l5 = qn();
$f5 = INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME;
if (function_exists("getrusage")) {
$z5 = getrusage();
$k5 = str_pad(
round(
$z5["ru_utime.tv_sec"] + $z5["ru_utime.tv_usec"] / 1000000,
5
),
10,
" ",
STR_PAD_RIGHT
);
} else {
$k5 = str_pad(round(dq() - $_stopwatch, 5), 10, " ", STR_PAD_RIGHT);
}
if ($e1[0] == "}") {
--$q5;
if ($q5 < 0) {
$q5 = 0;
}
}
$x5 = E2_RUN_ID . " " . $k5 . " " . str_repeat(" ", $q5 * 2) . $e1 . "\n";
if ($e1[strlen($e1) - 1] == "{") {
++$q5;
}
$iy = FILE_APPEND;
if (Log::$m5) {
@file_put_contents($f5, $x5, $iy);
@chmod($f5, E2_NEW_FILES_RIGHTS);
}
if ($l5 !== false) {
$od = INSTANCE_DIR . LOGS_DIRNAME . $l5 . ".log";
@nq(INSTANCE_DIR . LOGS_DIRNAME);
@file_put_contents($od, $x5, $iy);
@chmod($l5, E2_NEW_FILES_RIGHTS);
}
if ($e1[0] == "#") {
$e5 = INSTANCE_DIR . LOGS_DIRNAME . "debug.log";
@nq(dirname($e5) . "/");
@file_put_contents($e5, $x5, $iy);
@chmod($e5, E2_NEW_FILES_RIGHTS);
}
}
function ln($r5)
{
@e3(
USER_DIR . "ctree.php",
"<?php\r\n\r\n" . var_export($r5, true) . "\r\n\r\n?>php"
);
}
function zn()
{
$f5 = INSTANCE_DIR . LOGS_DIRNAME . MAIN_LOG_FILENAME;
@nq(INSTANCE_DIR . LOGS_DIRNAME);
@file_put_contents($f5, "");
@chmod($f5, E2_NEW_FILES_RIGHTS);
}
define(
"MAIL_ENABLED",
!in_array("mail", explode(",", ini_get("disable_functions")))
);
function kn($t5, $content)
{
$j5 = SYSTEM_DEFAULTS_DIR . "mail/" . $t5 . ".mtmpl.php";
if (is_file($j5)) {
ob_start();
include $j5;
$fa = ob_get_contents();
ob_end_clean();
return trim($fa);
}
}
function xn()
{
global $_config;
$h5 = $_config["mail_from"];
if ($h5[strlen($h5) - 1] == "@") {
$h5 .= $_SERVER["HTTP_HOST"];
}
return $h5;
}
function en($g5, $subject, $zq, $w5 = "")
{
global $_config;
if ($_config["dev_mail_debug"]) {
$w = "mail-debug";
$jv = basename(tempnam($w, "m-"));
$e1 =
"To: " .
$g5 .
"\n" .
"Subject: " .
$subject .
"\n" .
$w5 .
"\n" .
"--------------------------------------------------\n" .
$zq;
e3($w . "/" . $jv, $e1);
chmod($w . "/" . $jv, E2_NEW_FILES_RIGHTS);
rename($w . "/" . $jv, $w . "/" . $jv . ".txt");
}
$subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";
$w5 .= "\r\nContent-Type: text/plain; charset=utf-8";
if (MAIL_ENABLED) {
mail($g5, $subject, $zq, trim($w5));
}
}
function rn($parameters, $u5)
{
global $settings;
$i5["each"] = [];
$i5["reorderable?"] = false;
$hd = nf(true, true);
if ($hd === null or $hd === 0) {
return $i5;
}
if (!@$settings["appearance"]["show_main_menu"]) {
return $i5;
}
return $i5;
}
function tn($h2)
{
foreach ($h2 as $vl) {
if ($vl["visible?"]) {
return true;
}
}
return false;
}
function jn()
{
global $settings, $_strings, $_current_url;
$yj = sf();
return [
[
"sort-id" => "f",
"href" => eq("e2m_favourites", ["page" => 1]),
"content-classes" => ["favourites"],
"svg-id" => "favourite-on",
"title" => $_strings["nm--favourites"],
"current?" => AeMainMenuManager::$isFavouritesCurrent,
"parent?" => AeMainMenuManager::$isFavouritesParent,
"visible?" => (bool) @$settings["menu_items"]["favourites_on"],
"available?" => true,
],
[
"sort-id" => "h",
"href" => eq("e2m_most_commented", ["page" => 1]),
"content-classes" => ["most-commented"],
"svg-id" => "comments",
"title" => $_strings["nm--most-commented"],
"current?" => AeMainMenuManager::$isMostCommentedCurrent,
"parent?" => AeMainMenuManager::$isMostCommentedParent,
"visible?" => (bool) @$settings["menu_items"]["most_commented_on"],
"available?" => true,
],
[
"sort-id" => "p",
"href" => eq("e2m_popular", ["page" => 1]),
"content-classes" => ["popular"],
"svg-id" => "read",
"title" => $_strings["nm--most-read"],
"current?" => AeMainMenuManager::$isPopularCurrent,
"parent?" => AeMainMenuManager::$isPopularParent,
"visible?" => (bool) @$settings["menu_items"]["popular_on"],
"available?" => true,
],
[
"sort-id" => "t",
"href" => eq("e2m_tags"),
"svg-id" => "tags",
"title" => $_strings["gs--tags"],
"current?" => AeMainMenuManager::$isTagsCurrent,
"parent?" => AeMainMenuManager::$isTagsParent,
"visible?" => (bool) @$settings["menu_items"]["tags_on"],
"available?" => true,
],
[
"sort-id" => "c",
"href" => p(),
"content-classes" => ["day", "month", "year"],
"svg-id" => "calendar",
"title" => $_strings["gs--calendar"],
"current?" => AeMainMenuManager::$isCalendarCurrent,
"parent?" => AeMainMenuManager::$isCalendarParent,
"visible?" => (bool) @$settings["menu_items"]["calendar_on"],
"available?" => true,
],
[
"sort-id" => "r",
"href" => $yj ? $yj : eq("e2m_frontpage", ["page" => 1]),
"svg-id" => "dice",
"title" => $_strings["nm--random-note"],
"current?" => $_current_url === $yj,
"parent?" => false,
"visible?" =>
$yj !== false and (bool) @$settings["menu_items"]["random_on"],
"available?" => $yj !== false,
],
];
}
function hn($candy, $nj, $mj, $fj, $dj)
{
global $_config, $_template, $_newsfeeds, $_current_url, $_canonical_url;
$meta["base-href"] = AeEnv::$o;
$meta["current-href"] = $_current_url;
$meta["canonical-href"] = $_canonical_url;
$meta["stylesheets"] = y2();
$meta["scripts"] = n2();
$meta["newsfeeds"] = $_newsfeeds;
$meta["favicon-type"] = "image/x-icon";
$meta["favicon-href"] = "favicon.ico";
if ($sj = tv()) {
$meta["favicon-type"] = dd($sj);
$meta["favicon-href"] = $sj;
$meta["apple-touch-icon-href"] = tv("square");
}
$meta["navigation-links"] = [
[
"rel" => "index",
"href" => eq("e2m_frontpage", ["page" => 1]),
"id" => "link-index",
],
];
if (!empty($dj)) {
foreach (["prev", "next", "earlier", "later"] as $aj) {
if (array_key_exists($aj . "-href", $dj)) {
$qj = $aj;
if ($aj == "earlier") {
$qj = "prev";
}
if ($aj == "later") {
$qj = "next";
}
$s1 = $dj[$aj . "-href"];
if ($s1 === "javascript:;") {
continue;
}
$meta["navigation-links"][] = [
"rel" => $qj,
"href" => $s1,
"id" => "link-" . $aj,
];
}
}
}
if (!isset($_template)) {
kf();
}
$meta["viewport"] = $_template["meta_viewport"];
if (is_file($_config["path_media"] . "manifest.json")) {
$meta["manifest-href"] = AeEnv::$o . "manifest.json";
}
$meta["og-images"] = [];
if (is_array($nj["only"]["og-images"])) {
$meta["og-images"] = $nj["only"]["og-images"];
$meta["twitter-card"] = "summary_large_image";
}
if (is_array(@$mj["og-images"])) {
$meta["og-images"] = $mj["og-images"];
$meta["twitter-card"] = "summary_large_image";
}
if (!count($meta["og-images"])) {
$meta["og-images"] = [$fj["userpic-large-href"]];
$meta["twitter-card"] = "summary";
}
return $meta;
}
function gn(AeDatabaseConfiguration $databaseConfiguration)
{
$lj = $databaseConfiguration->getSubset();
if ($lj < 1) {
throw new LogicException(
"Subset to set in place of zero must be greater than 0"
);
}
dm($databaseConfiguration, "prepare migrate db");
am($databaseConfiguration, "SET sql_quote_show_create=1");
}
function wn(AeDatabaseConfiguration $databaseConfiguration)
{
$prefix = $databaseConfiguration->getPrefix();
$lj = $databaseConfiguration->getSubset();
if ($lj < 1) {
throw new LogicException(
"Subset to set in place of zero must be greater than 0"
);
}
dm($databaseConfiguration, "migrate db");
am($databaseConfiguration, "SET sql_quote_show_create=1");
un($databaseConfiguration);
if (Log::$a) {
__log("Fix problems with table structure {");
}
$zj = false;
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
nm($databaseConfiguration, $l2);
am($databaseConfiguration, "SHOW CREATE TABLE `" . $prefix . $l2 . "`");
$kj[$l2] = qm();
$kj[$l2] = $kj[$l2][0]["Create Table"];
am($databaseConfiguration, "SHOW INDEX FROM `" . $prefix . $l2 . "`");
$xj = qm();
$ej = [];
$rj = [];
foreach ($xj as $mb) {
$mb = $mb["Key_name"];
if (
preg_match('/\_[0-9]+$/', $mb) or
$l2 === "Actions" and $mb === "EntityID" or
$l2 === "GIPsSessions" and $mb === "GIP" or
$l2 === "GIPsSessions" and $mb === "SubsetID" or
$l2 === "Notes" and $mb === "Title"
) {
$ej[] = $mb;
$rj[] = "DROP INDEX `" . $mb . "`";
}
if ($l2 === "Actions" and $mb === "EntityID") {
$zj = true;
}
if ($l2 === "Actions" and $mb === "EntityIDStamp") {
$zj = true;
}
}
if (count($rj)) {
$rj = implode(", ", array_unique($rj));
$ej = implode(", ", array_unique($ej));
if (Log::$a) {
__log(
'Drop erroneous index "' .
$ej .
'" on "' .
$prefix .
$l2 .
'"'
);
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . $l2 . "` " . $rj
);
}
if (!strstr($kj[$l2], "InnoDB")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . $l2 . "` " . "ENGINE = InnoDB"
);
}
if (!strstr($kj[$l2], "`SubsetID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
$l2 .
"` " .
"ADD `SubsetID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `ID`"
);
}
if (
$l2 === "Actions" and
strstr($kj["Actions"], "`ReadCount`") and
!$zj
) {
in($databaseConfiguration);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
$l2 .
"` " .
"SET `SubsetID` = " .
$lj .
" " .
"WHERE `SubsetID` = 0"
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Ensure modern table structure {");
}
if (!strstr($kj["Actions"], "`ReadCount`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Actions` " .
"ADD `ReadCount` INT DEFAULT '0' NOT NULL"
);
}
if (strstr($kj["Actions"], "`HitCount`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Actions` " . "DROP `HitCount`"
);
am(
$databaseConfiguration,
"DELETE FROM `" . $prefix . "Actions` " . "WHERE `ReadCount` = 0"
);
}
if (!strstr($kj["Aliases"], "`EntityType`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Aliases` " .
"ADD `EntityType` VARCHAR( 1 ) DEFAULT '' NOT NULL AFTER `ID`"
);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Aliases` " .
"SET `EntityType` = 'n' " .
"WHERE `EntityType` = ''"
);
am(
$databaseConfiguration,
"DELETE FROM `" .
$prefix .
"Aliases` " .
"WHERE `ID` IN (" .
"SELECT `ID` FROM (" .
"SELECT a.`ID` FROM `" .
$prefix .
"Aliases` a " .
"LEFT OUTER JOIN `" .
$prefix .
"Keywords` e " .
"ON a.`EntityID` = e.`ID` " .
"WHERE a.`EntityType` = 't' " .
"AND e.`ID` IS NULL" .
") AS temp" .
")",
"clean up leaked tag aliases"
);
if (!stristr($kj["Comments"], "`Text` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"CHANGE `Text` `Text` MEDIUMTEXT"
);
}
if (!stristr($kj["Comments"], "`Reply` MEDIUMTEXT")) {
if (strstr($kj["Comments"], "`Reply`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"CHANGE `Reply` `Reply` MEDIUMTEXT"
);
} else {
if (Log::$a) {
__log(
"No Reply column in comments; ignored assuming a 2.11 database"
);
}
}
}
if (!stristr($kj["Comments"], "`IP` VARCHAR(39)")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"CHANGE `IP` `IP` VARCHAR(39) DEFAULT '' NOT NULL"
);
}
if (!strstr($kj["Comments"], "`IsGIPUsed`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"ADD `IsGIPUsed` TINYINT(1) DEFAULT '0' NOT NULL AFTER `IP`"
);
}
if (!strstr($kj["Comments"], "`GIP`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"ADD `GIP` VARCHAR(15) DEFAULT '' NOT NULL AFTER `IsGIPUsed`"
);
}
if (!strstr($kj["Comments"], "`GIPAuthorID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Comments` " .
"ADD `GIPAuthorID` VARCHAR(64) DEFAULT '' NOT NULL AFTER `GIP`"
);
}
if (strstr($kj["Comments"], "`SocialType`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Comments` " . "DROP `SocialType`"
);
}
if (strstr($kj["Comments"], "`SocialID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Comments` " . "DROP `SocialID`"
);
}
if (!strstr($kj["GIPsSessions"], "`AuthorEmail`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"GIPsSessions` " .
"ADD `AuthorEmail` VARCHAR(255) DEFAULT '' NOT NULL AFTER `AuthorName`"
);
}
if (!strstr($kj["GIPsSessions"], "`AuthorProfileLink`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"GIPsSessions` " .
"ADD `AuthorProfileLink` VARCHAR(255) DEFAULT '' NOT NULL AFTER `AuthorEmail`"
);
}
if (strstr($kj["Keywords"], "`ParentKeywordID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Keywords` " . "DROP `ParentKeywordID`"
);
}
if (!strstr($kj["Keywords"], "`OriginalAlias`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"CHANGE `URLName` `OriginalAlias` VARCHAR( 64 ) DEFAULT '' NOT NULL AFTER `Keyword`"
);
}
if (!strstr($kj["Keywords"], "`PageTitle`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `PageTitle` VARCHAR(255) DEFAULT '' NOT NULL AFTER `OriginalAlias`"
);
}
if (!stristr($kj["Keywords"], "`Description` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"CHANGE `Description` `Description` MEDIUMTEXT"
);
}
if (!strstr($kj["Keywords"], "`Summary`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `Summary` MEDIUMTEXT AFTER `Description`"
);
}
if (!strstr($kj["Keywords"], "`Uploads`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `Uploads` MEDIUMTEXT AFTER `Summary`"
);
}
if (!stristr($kj["Keywords"], "`Uploads` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"CHANGE `Uploads` `Uploads` MEDIUMTEXT"
);
}
if (!strstr($kj["Keywords"], "`IsVisible`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Keywords` " .
"ADD `IsVisible` TINYINT(1) DEFAULT '1' NOT NULL AFTER `Uploads`"
);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Keywords` SET `Summary` = '' WHERE `Summary` IS NULL"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Keywords` SET `Uploads` = '' WHERE `Uploads` IS NULL"
);
if (!strstr($kj["Notes"], "`FormatterID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `FormatterID` VARCHAR( 32 ) DEFAULT '" .
DEFAULT_FORMATTER .
"' NOT NULL AFTER `Text`"
);
}
if (1) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `FormatterID` `FormatterID` VARCHAR( 32 ) DEFAULT '" .
DEFAULT_FORMATTER .
"' NOT NULL"
);
}
if (!strstr($kj["Notes"], "`OriginalAlias`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `URLName` `OriginalAlias` VARCHAR( 64 ) DEFAULT '' NOT NULL AFTER `FormatterID`"
);
}
if (strstr($kj["Notes"], "`IP`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP `IP`"
);
}
if (!stristr($kj["Notes"], "`Text` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `Text` `Text` MEDIUMTEXT"
);
}
if (!strstr($kj["Notes"], "`Summary`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `Summary` MEDIUMTEXT AFTER `Text`"
);
}
if (!strstr($kj["Notes"], "`IsIndexed`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `IsIndexed` TINYINT( 1 ) DEFAULT '0' NOT NULL AFTER `IsDST`"
);
}
if (!strstr($kj["Notes"], "`Uploads`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `Uploads` MEDIUMTEXT AFTER `OriginalAlias`"
);
}
if (!stristr($kj["Notes"], "`Uploads` MEDIUMTEXT")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"CHANGE `Uploads` `Uploads` MEDIUMTEXT"
);
}
if (!strstr($kj["Notes"], "`IsExternal`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `IsExternal` TINYINT(1) DEFAULT '0' NOT NULL AFTER `IsIndexed`"
);
}
if (!strstr($kj["Notes"], "`SourceID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `IsExternal`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `SourceID`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteURL`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteURL` VARCHAR(255) DEFAULT '' NOT NULL AFTER `SourceNoteID`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteData`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteData` MEDIUMTEXT AFTER `SourceNoteURL`"
);
}
if (!strstr($kj["Notes"], "`SourceNoteJSONURL`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `SourceNoteJSONURL` VARCHAR(255) DEFAULT '' NOT NULL AFTER `SourceNoteData`"
);
}
if (strstr($kj["Notes"], "`SourceMainImageURL`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP `SourceMainImageURL`"
);
}
if (strstr($kj["Notes"], "`IsIssue`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP `IsIssue`"
);
}
if (!strstr($kj["Notes"], "`ReadCount`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Notes` " .
"ADD `ReadCount` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `IsExternal`"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` n JOIN (" .
"SELECT `EntityID`, SUM(`ReadCount`) `AggregateReadCount` " .
"FROM `" .
$prefix .
"Actions` " .
"GROUP BY `EntityID`" .
") a ON n.`ID` = a.`EntityID` " .
"SET `ReadCount` = `AggregateReadCount`"
);
}
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` SET `Summary` = '' WHERE `Summary` IS NULL"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` SET `Uploads` = '' WHERE `Uploads` IS NULL"
);
am(
$databaseConfiguration,
"UPDATE `" .
$prefix .
"Notes` SET `SourceNoteData` = '' WHERE `SourceNoteData` IS NULL"
);
if (!strstr($kj["Sources"], "`TrueID`")) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Sources` " .
"ADD `TrueID` INT UNSIGNED DEFAULT '0' NOT NULL AFTER `ID`"
);
am(
$databaseConfiguration,
"UPDATE `" . $prefix . "Sources` " . "SET `TrueID` = `ID`"
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Ensure indexes {");
}
if (strstr($kj["Notes"], "`Title` (`Title`(191))")) {
if (Log::$a) {
__log('Drop erroneous index on "' . $prefix . 'Notes.Title"');
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . "Notes` " . "DROP INDEX `Title`"
);
}
on($databaseConfiguration);
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
foreach (AeModel::indexesByUnprefixedTableName($l2) as $mb) {
list($type, $fb) = $mb;
$db = implode("", $fb);
$tj =
AeModel::indexCheckSQLByIndexType($type) .
" `" .
$db .
"` (`" .
implode("`,`", $fb) .
"`)";
$sb =
AeModel::indexCreateSQLByIndexType($type) .
" `" .
$db .
"` (`" .
implode("`, `", $fb) .
"`)";
if (!strstr($kj[$l2], $tj)) {
if (Log::$a) {
__log(
'Table "' .
$prefix .
$l2 .
'" is missing "' .
AeModel::indexCheckSQLByIndexType($type) .
'" on columns "' .
implode('", "', $fb) .
'"'
);
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $prefix . $l2 . "` " . "ADD " . $sb
);
}
}
}
if (Log::$a) {
__log("}");
}
return true;
}
function un(AeDatabaseConfiguration $databaseConfiguration)
{
if (Log::$a) {
__log("Ensure encoding utf8mb4 on all native tables {");
}
foreach (AeModel::unprefixedCoreTablesNames() as $jj) {
$hj = $databaseConfiguration->getPrefix() . $jj;
if (Log::$a) {
__log("Migrate: Check table " . $hj);
}
$gj = ym($databaseConfiguration, $jj);
if (!$gj) {
continue;
}
if (stripos($gj["Collation"], "utf8mb4") === 0) {
continue;
}
if (Log::$a) {
__log("Migrate: Table " . $hj . " has a wrong encoding");
}
if (Log::$a) {
__log("Migrate: Drop indexes of table " . $hj);
}
am(
$databaseConfiguration,
"SHOW INDEX FROM `" .
$hj .
"` " .
"WHERE `Key_name` <> 'PRIMARY' " .
"AND `Seq_in_index` = 1",
"show indexes from table " . $hj
);
$xj = qm();
foreach ($xj as $mb) {
am(
$databaseConfiguration,
"ALTER TABLE `" .
$hj .
"` " .
"DROP INDEX `" .
$mb["Key_name"] .
"`",
"drop index " . $mb["Key_name"]
);
}
if (Log::$a) {
__log("Migrate: Convert table " . $hj . " to utf8mb4");
}
am(
$databaseConfiguration,
"ALTER TABLE `" . $hj . "` " . "CONVERT TO CHARACTER SET utf8mb4",
"convert table to character set utf8mb4"
);
}
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Ensure encoding utf8mb4 on all Rose tables {");
}
foreach (td() as $wj) {
$hj = $databaseConfiguration->getPrefix() . SEARCH_EXTRA_PREFIX . $wj;
if (Log::$a) {
__log("Migrate: Check table " . $hj);
}
$gj = ym($databaseConfiguration, SEARCH_EXTRA_PREFIX . $wj);
if (!$gj) {
continue;
}
if (stripos($gj["Collation"], "utf8mb4") === 0) {
continue;
}
if (Log::$a) {
__log(
"Some Rose tables have a wrong encoding, will need to erase and recreate them all"
);
}
wd($databaseConfiguration);
break;
}
if (Log::$a) {
__log("}");
}
}
function in(AeDatabaseConfiguration $databaseConfiguration)
{
$prefix = $databaseConfiguration->getPrefix();
if (Log::$a) {
__log(
'Table "' .
$prefix .
'Actions" is missing necessary UNIQUE index, must rearrange {'
);
}
am(
$databaseConfiguration,
"DROP TABLE IF EXISTS `" . $prefix . "Actions_Fixed`",
"remove temporary Actions_Fixed table if exists"
);
am(
$databaseConfiguration,
"CREATE TABLE `" .
$prefix .
"Actions_Fixed` " .
"LIKE `" .
$prefix .
"Actions`",
"create new temporary Actions_Fixed table"
);
am(
$databaseConfiguration,
"ALTER TABLE `" .
$prefix .
"Actions_Fixed` " .
"ADD UNIQUE INDEX(`EntityID`, `Stamp`)",
"add UNIQUE index to the temporary Actions_Fixed table"
);
am(
$databaseConfiguration,
"INSERT INTO `" .
$prefix .
"Actions_Fixed` (`SubsetID`, `EntityID`, `Stamp`, `ReadCount`) " .
"SELECT `SubsetID`, `EntityID`, `Stamp`, `AggregateReadCount` FROM (" .
"SELECT `SubsetID`, `EntityID`, `Stamp`, SUM(`ReadCount`) `AggregateReadCount` " .
"FROM `" .
$prefix .
"Actions` " .
"GROUP BY `EntityID`, `Stamp`" .
") `" .
$prefix .
"Actions_Fixed_AliasRequiredForNoReason`",
"rearrange Actions records from existing problematic Actions table to the new temporary Actions_Fixed table"
);
am(
$databaseConfiguration,
"RENAME TABLE `" .
$prefix .
"Actions` TO `" .
$prefix .
"Actions_Corrupt`",
"rename Actions to Actions_Corrupt"
);
am(
$databaseConfiguration,
"RENAME TABLE `" .
$prefix .
"Actions_Fixed` TO `" .
$prefix .
"Actions`",
"rename Actions_Fixed to Actions"
);
am(
$databaseConfiguration,
"DROP TABLE `" . $prefix . "Actions_Corrupt`",
"remove Actions_Corrupt table"
);
if (Log::$a) {
__log("}");
}
}
function on($databaseConfiguration)
{
global $_db;
$uj =
"(0 " .
"OR `Text` LIKE '%!!%' " .
"OR `Text` LIKE '%||%' " .
"OR `Text` LIKE '%\%\%%' " .
"OR `Text` LIKE '%##%' " .
"OR `Text` LIKE '%++%' " .
"OR `Text` LIKE '%((html%' " .
"OR `Text` LIKE '%((img%' " .
"OR `Text` LIKE '%((link%' " .
"OR `Text` LIKE '%((%.jpg%' " .
"OR `Text` LIKE '%((%.jpeg%' " .
"OR `Text` LIKE '%((%.gif%' " .
"OR `Text` LIKE '%((%.png%' " .
"OR `Text` LIKE '%((%.webp%' " .
"OR `Text` LIKE '%[[html%' " .
"OR `Text` LIKE '%[[img%' " .
"OR `Text` LIKE '%[[link%' " .
"OR `Text` LIKE '%[[%.jpg%' " .
"OR `Text` LIKE '%[[%.jpeg%' " .
"OR `Text` LIKE '%[[%.gif%' " .
"OR `Text` LIKE '%[[%.png%' " .
"OR `Text` LIKE '%[[%.webp%' " .
")";
if (Log::$a) {
__log("Switch from Calliope to Neasden {");
}
am(
$databaseConfiguration,
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"SET `FormatterID` = 'neasden' " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `FormatterID` = 'calliope' " .
"AND (" .
"`IsPublished` = '0' " .
"OR (" .
"`IsPublished` = '1' " .
"AND !" .
$uj .
")" .
")"
);
if (Log::$a) {
__log(
mysqli_affected_rows($_db["link"]) .
" drafts and notes with simple formatting switched"
);
}
am(
$databaseConfiguration,
"SELECT `ID` FROM `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `FormatterID` = 'calliope'"
);
$ff = qm();
if (Log::$a) {
__log(count($ff) . " with complex formatting remain");
}
if (count($ff) > 0) {
$gv = "AEGEA-LEGACY-REVIEW";
$ij = aa($databaseConfiguration, $gv);
if (!$ij) {
$ij["ID"] = fa($databaseConfiguration, $gv, false);
}
if (Log::$a) {
__log('Tag "' . $gv . '" has ID ' . $ij["ID"]);
}
foreach ($ff as $zy) {
sm(
"INSERT INTO `" .
$databaseConfiguration->getPrefix() .
"NotesKeywords` " .
"(`SubsetID`, `NoteID`, `KeywordID`) " .
"VALUES (" .
((int) $databaseConfiguration->getSubset()) .
", " .
((int) $zy["ID"]) .
", " .
((int) $ij["ID"]) .
")",
"add new tag bindings"
);
}
$il = "Aegea legacy notes for review";
$bq =
"These notes were automatically converted from a very old version of Aegea and may have formatting problems. Please edit them to fix these problems. When finished, just delete this tag.";
am(
$databaseConfiguration,
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Keywords` " .
"SET `IsVisible` = 0, `IsFavourite` = 1, " .
"`PageTitle` = '" .
$il .
"', " .
"`Description` = '" .
$bq .
"' " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `ID` = " .
$ij["ID"]
);
am(
$databaseConfiguration,
"UPDATE `" .
$databaseConfiguration->getPrefix() .
"Notes` " .
"SET `FormatterID` = 'neasden' " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND `FormatterID` = 'calliope'"
);
if (Log::$a) {
__log(
"Switched " .
mysqli_affected_rows($_db["link"]) .
" notes with complex formatting"
);
}
}
if (Log::$a) {
__log("}");
}
}
function pn(AeDatabaseConfiguration $databaseConfiguration)
{
global $_db;
$oj = false;
$pj = [];
$sql =
"SHOW TABLES FROM `" .
mysqli_real_escape_string($_db["link"], $databaseConfiguration->name) .
"`";
if (Log::$a) {
__log("DB [?]: " . $sql);
}
$h3 = mysqli_query($_db["link"], $sql);
if ($h3) {
while ($j2 = mysqli_fetch_row($h3)) {
foreach (AeModel::unprefixedCoreTablesNames() as $jj) {
if (
strcasecmp(
$j2[0],
$databaseConfiguration->getPrefix() . $jj
) === 0
) {
$oj = true;
$pj[] = $jj;
}
}
}
}
$ch = true;
foreach (AeModel::unprefixedCoreTablesNames() as $jj) {
if (!in_array($jj, $pj)) {
$ch = false;
}
}
$vh = true;
foreach (AeModel::unprefixedEssentialTablesNames() as $jj) {
if (!in_array($jj, $pj)) {
$vh = false;
}
}
return ["occupied" => $oj, "complete" => $ch, "migrateable" => $vh];
}
function cm($databaseConfiguration)
{
dm($databaseConfiguration);
$yt = pn($databaseConfiguration);
if (!$yt["occupied"]) {
throw new AeMySQLNoDataException("Database is empty");
}
if (!$yt["migrateable"]) {
throw new AeMySQLNotMigrateableException("Database is not migrateable");
}
}
function vm(AeDatabaseConfiguration $databaseConfiguration)
{
global $vs;
if (
($ix = mysqli_connect(
"p:" . $databaseConfiguration->host,
$databaseConfiguration->user,
ks($databaseConfiguration->password),
"",
$databaseConfiguration->port
)) === false
) {
return [];
}
$tt = [];
$bh = ["information_schema", "performance_schema", "sys", "mysql"];
@$vs++;
$e2_ = "SHOW DATABASES";
if (Log::$a) {
__log("DB [" . $vs . "]: " . $e2_);
}
$h3 = mysqli_query($ix, $e2_);
if ($h3 === false) {
throw new AeMySQLQueryException(
"Could not list databases\n\nMySQL says:\n" . mysqli_error($ix)
);
}
while ($j2 = mysqli_fetch_row($h3)) {
if (mysqli_select_db($ix, $j2[0]) and !in_array($j2[0], $bh)) {
$tt[] = $j2[0];
}
}
return $tt;
}
function bm($databaseConfiguration, $l2)
{
am(
$databaseConfiguration,
"SHOW TABLES LIKE '" . $databaseConfiguration->getPrefix() . $l2 . "'"
);
$dr = qm();
return count($dr) > 0;
}
function ym($databaseConfiguration, $l2)
{
am(
$databaseConfiguration,
"SHOW TABLE STATUS LIKE '" .
$databaseConfiguration->getPrefix() .
$l2 .
"'"
);
$h3 = qm();
return $h3 ? $h3[0] : [];
}
function nm($databaseConfiguration, $l2)
{
if (bm($databaseConfiguration, $l2)) {
return;
}
am(
$databaseConfiguration,
"CREATE TABLE `" .
$databaseConfiguration->getPrefix() .
$l2 .
"` " .
AeModel::columnsAndIndexesSQLByUnprefixedTableName($l2) .
" " .
"ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
);
}
function mm(
AeDatabaseConfiguration $databaseConfiguration,
$l2,
$u4,
$oz = "INSERT",
$yh = ""
) {
global $_db;
$nh["SubsetID"] = $databaseConfiguration->getSubset();
foreach ($u4 as $k3 => $x3) {
$nh[$k3] = "'" . lm($x3) . "'";
}
$mh = "`" . implode("`, `", array_keys($nh)) . "`";
$fh = implode(", ", array_values($nh));
am(
$databaseConfiguration,
$oz .
" INTO `" .
$databaseConfiguration->getPrefix() .
$l2 .
"` " .
"(" .
$mh .
") VALUES (" .
$fh .
")" .
($yh ? " " . $yh : "")
);
$u4["ID"] = mysqli_insert_id($_db["link"]);
return $u4;
}
function fm(
AeDatabaseConfiguration $databaseConfiguration,
$l2,
$u4,
$dh = false,
$sh = false
) {
if (Log::$a) {
__log("Model: update record in table " . $l2 . " {");
}
$ah = [];
foreach (AeModel::softFieldsByUnprefixedTableName($l2) as $x) {
if (array_key_exists($x, $u4)) {
$ah[] = "`" . $x . "`" . "='" . lm($u4[$x]) . "'";
}
}
$qh = [];
if (is_array($dh)) {
foreach (AeModel::softFieldsByUnprefixedTableName($l2) as $x) {
if (array_key_exists($x, $dh)) {
$qh[] = "`" . $x . "`" . "='" . lm($dh[$x]) . "'";
}
}
}
if (count($qh)) {
$m1 = implode(" AND ", $qh);
} else {
if (!array_key_exists("ID", $u4) or !is_numeric($u4["ID"])) {
if (Log::$a) {
__log(
'Error: e2_update_record must be called with an ID field in $record when updating single row'
);
}
return false;
}
$m1 = "`ID`=" . $u4["ID"];
}
if (count($ah) > 0) {
$lh = $sh ? "LOW_PRIORITY " : "";
am(
$databaseConfiguration,
"UPDATE " .
$lh .
"`" .
$databaseConfiguration->getPrefix() .
$l2 .
"` " .
"SET " .
implode(", ", $ah) .
" " .
"WHERE `SubsetID`=" .
$databaseConfiguration->getSubset() .
" " .
"AND (" .
$m1 .
")"
);
}
if (Log::$a) {
__log("}");
}
return true;
}
define("E2_MYSQL_CONNECT_TIMEOUT", 5);
function dm(AeDatabaseConfiguration $databaseConfiguration, $zh = "")
{
static $kh = false;
static $xh = false;
global $_instance_config, $_db, $vs;
if ($kh !== $databaseConfiguration->getServerKeyString()) {
if (Log::$a) {
__log(
'Ensure: Establishing connection "' .
$databaseConfiguration->getServerKeyString() .
'"'
);
}
if ($kh !== false) {
if (Log::$a) {
__log("Closing previous database connection");
}
mysqli_close($_db["link"]);
}
$eh = mysqli_init();
$eh->options(MYSQLI_OPT_CONNECT_TIMEOUT, E2_MYSQL_CONNECT_TIMEOUT);
if (
$_instance_config["dev_chaos"] and
!rand(0, 1 / $_instance_config["dev_chaos"] - 1)
) {
throw new AeMySQLCannotConnectException(
"Could not " . $zh . "\n\nChaos"
);
}
$rh = @mysqli_real_connect(
$eh,
"p:" . $databaseConfiguration->host,
$databaseConfiguration->user,
ks($databaseConfiguration->password),
"",
$databaseConfiguration->port
);
if (!$rh) {
$y2 = mysqli_connect_errno();
if (1045 === $y2) {
throw new AeMySQLAccessDeniedException(
"Could not " . $zh . " (" . $y2 . ")"
);
} else {
throw new AeMySQLCannotConnectException(
"Could not " . $zh . " (" . $y2 . ")"
);
}
}
if (!xm($eh)) {
throw new AeMySQLTooOldException("Could not " . $zh);
}
$_db["link"] = $eh;
$kh = $databaseConfiguration->getServerKeyString();
$xh = false;
}
if ($xh !== $databaseConfiguration->name) {
if (Log::$a) {
__log(
'Ensure: Selecting database "' .
$databaseConfiguration->name .
'"'
);
}
if (!@mysqli_select_db($_db["link"], $databaseConfiguration->name)) {
throw new AeMySQLNotFoundException("Could not " . $zh);
}
$e2_ = "SET NAMES utf8mb4";
mysqli_query($_db["link"], $e2_);
@$vs++;
if (Log::$a) {
__log("DB [" . $vs . "]: " . $e2_);
}
$xh = $databaseConfiguration->name;
}
}
function sm($e2_, $zh = "run some query")
{
$databaseConfiguration = bl();
return am($databaseConfiguration, $e2_, $zh);
}
function am($databaseConfiguration, $e2_, $zh = "")
{
global $vs, $_db, $_config;
dm($databaseConfiguration, $zh);
if ($_config["dev_chaos"] and !rand(0, 1 / $_config["dev_chaos"] - 1)) {
throw new AeMySQLQueryException(
"Could not " . $zh . "\n\nChaos in e2_mysql_query"
);
}
@$vs++;
if (Log::$a) {
if ($zh) {
__log("Will " . $zh);
}
}
if (Log::$a) {
__log("DB [" . $vs . "]: " . $e2_);
}
$_db["result"] = @mysqli_query($_db["link"], $e2_);
if ($_db["result"]) {
if ($_config["backup_tail"]) {
if (stripos($e2_, "SELECT") !== 0 and stripos($e2_, "SHOW") !== 0) {
$od = $databaseConfiguration->backup_dir . "backup-tail.sql";
@file_put_contents(
$od,
$e2_ . ";\r\n\r\n",
FILE_APPEND | LOCK_EX
);
@chmod($od, E2_NEW_FILES_RIGHTS);
}
}
} else {
throw new AeMySQLQueryException(
"Could not " .
$zh .
"\n\nMySQL says:\n" .
mysqli_error($_db["link"])
);
}
}
function qm($type = MYSQLI_ASSOC)
{
global $_db;
$vb = [];
while ($p5 = @mysqli_fetch_array($_db["result"], $type)) {
foreach ($p5 as $gb => $th) {
if (is_string($th)) {
$p5[$gb] = $th;
}
}
$vb[] = $p5;
}
return $vb;
}
function lm($m4)
{
global $_db;
dm(bl(), "escape string");
return mysqli_real_escape_string($_db["link"], (string) $m4);
}
function zm()
{
global $_config;
$tv = array_keys(km(USER_DIR . BACKUP_DIRNAME));
if (Log::$a) {
__log("Backup: Found " . count($tv) . " backups");
}
if (count($tv)) {
$jh = time() - $tv[0];
$hh = $jh >= $_config["backup_rebase_interval"];
if (Log::$a) {
__log("Backup: " . $jh . " seconds since last backup");
}
} else {
$hh = true;
}
if ($hh) {
if (Log::$a) {
__log("Backup: Will rebuild backup");
}
vv(eq("e2s_dump", []), true);
}
}
function km($backup_dir)
{
$tv = [];
foreach (glob($backup_dir . "*.sql") as $s2) {
if (
preg_match(
'/^backup\-(\d+)\-(\d+)\-(\d+)\-at\-(\d+)\-(\d+)\-(\d+)\.sql$/is',
basename($s2),
$v6
)
) {
list(, $gm, $wm, $um, $gh, $gb, $wh) = $v6;
$mf = gmmktime(
(int) $gh,
(int) $gb,
(int) $wh,
(int) $wm,
(int) $um,
(int) $gm
);
$tv[$mf] = $s2;
}
}
krsort($tv);
return $tv;
}
function xm($eh)
{
global $_db;
$_db["software"] = "MySQL";
$_db["version-minimum"] = E2_MINIMUM_MYSQL;
$_db["version"] = mysqli_get_server_info($eh);
$ih = strpos($_db["version"], "-MariaDB");
if ($ih !== false) {
$_db["software"] = "MariaDB";
$_db["version-minimum"] = E2_MINIMUM_MARIADB;
$_db["version"] = substr($_db["version"], 0, $ih);
if (substr($_db["version"], 0, 6) === "5.5.5-") {
$_db["version"] = substr($_db["version"], 6);
}
}
if (Log::$a) {
__log(
'Ensure: Running on "' .
$_db["software"] .
'", version "' .
$_db["version"] .
'"'
);
}
return version_compare($_db["version"], $_db["version-minimum"], ">=");
}
function em($backup_dir)
{
$tv = km($backup_dir);
$oh = [
SECONDS_IN_A_MINUTE,
SECONDS_IN_AN_HOUR,
SECONDS_IN_A_DAY,
SECONDS_IN_A_WEEK,
SECONDS_IN_A_MONTH,
-1,
];
$ph = count($tv);
$c8 = count($oh) - 1;
if ($ph > $c8) {
if (Log::$a) {
__log(
"Stored are " . $ph . " backups, over " . $c8 . ", will sift..."
);
}
$v8 = -1;
$gb = 0;
foreach ($tv as $mf => $s2) {
if (Log::$a) {
__log("Backup " . $s2 . " (" . gmdate("r", $mf) . ")");
}
if ($v8 == -1) {
if (Log::$a) {
__log("is latest, leave");
}
$v8 = $mf;
} elseif ($oh[$gb] == -1) {
if (Log::$a) {
__log("is too old, remove");
}
@unlink($s2);
} else {
if ($v8 - $mf < $oh[$gb]) {
if (Log::$a) {
__log(
"is not from long ago (within interval of " .
$oh[$gb] .
"s), remove"
);
}
@unlink($s2);
} else {
$gb++;
if (Log::$a) {
__log(
"is long enough ago, leave (proceed to interval of " .
$oh[$gb] .
"s)"
);
}
$v8 = $mf;
}
}
}
} else {
if (Log::$a) {
__log("No need to sift");
}
}
return;
}
function rm(AeDatabaseConfiguration $databaseConfiguration)
{
global $_db;
if (Log::$a) {
__log("Backup to " . $databaseConfiguration->backup_dir);
}
dm($databaseConfiguration, "make backup");
$nd = [];
foreach (AeModel::unprefixedCoreTablesNames() as $l2) {
$nd[] = $databaseConfiguration->getPrefix() . $l2;
}
$l = time();
$od =
$databaseConfiguration->backup_dir .
"backup-" .
gmdate('Y-m-d-\a\t-H-i-s', $l) .
".sql";
if ($databaseConfiguration->hasSubsetSpecified()) {
$subset = $databaseConfiguration->getSubset();
} else {
$subset = null;
}
e2_backup($_db["link"], $nd, $subset, $od);
@unlink($databaseConfiguration->backup_dir . "backup-tail.sql");
em($databaseConfiguration->backup_dir);
return $od;
}
function tm($b8)
{
$y8 = parse_url($b8);
$n8 = @$y8["host"];
$m8 = @$y8["port"];
if ((string) $n8 === "") {
$n8 = $b8;
$m8 = "";
}
return [$n8, $m8];
}
function e2s_dump()
{
global $_config;
if (!$_config["allow_underhood_access"]) {
z1(eq("e2m_settings"));
}
if ($_SERVER["REQUEST_METHOD"] != "POST") {
z1(eq("e2m_underhood"));
}
if (rm(bl())) {
hb("Backed up", E2E_MESSAGE);
}
z1(eq("e2m_underhood"));
}
function e2m_note($parameters = [])
{
global $settings, $_config, $_strings;
if (Log::$a) {
__log("Note {");
}
$zy = @$parameters["*note"];
if ($zy == false) {
return e2m_error404();
}
$f8 = af($zy);
$sf = ff($zy);
$gn = ys();
$d8 = $parameters["preview-key"] == $f8;
if (!empty($parameters["preview-key"]) and !$d8) {
return e2m_error404();
}
if (!$gn and !$d8 and $sf !== "public") {
return e2m_error404();
}
if (!empty($parameters["preview-key"]) and $sf === "public") {
unset($parameters["preview-key"]);
$na = eq("e2m_note", $parameters);
z1($na);
}
$na = eq("e2m_note", $parameters);
$noteView = new AeNoteView($zy);
$noteView->setWantReadHref($_config["count_reads"]);
$noteView->setWantControls($gn and !@$_config["read_only"]);
$noteView->setWantHiddenTags($gn);
if ($sf === "draft" or $sf === "scheduled") {
if (!$d8) {
$s8 = [
".note-id" => $zy["ID"],
"form-action" => eq("e2s_note_publish"),
"submit-text" => $_strings["fb--publish-note"],
"can-schedule?" => false,
"can-publish?" => !@$_config["read_only"],
"scheduling-promo" => e2l_get_string("pm--scheduling", [
"url" => $_config["paid_features_url"],
]),
];
}
}
$a8 = "";
$q8 = [];
$dj = [];
if ($sf === "public") {
$noteView->setWantNewCommentsCount($gn);
$noteView->setWantSharingButtons(
@$settings["appearance"]["show_sharing_buttons"]
);
$noteView->setWantRelatedNotes(true);
}
if ($sf === "public" or $sf === "hidden") {
if (Log::$a) {
__log("Navigation {");
}
$l8 = um($zy, "prev");
$z8 = um($zy, "next");
if ($l8) {
$dj["prev-href"] = eq("e2m_note", ["*note" => $l8]);
$dj["prev-title"] = ay(
htmlspecialchars($l8["Title"], ENT_NOQUOTES, "UTF-8")
);
}
if ($z8) {
$dj["next-href"] = eq("e2m_note", ["*note" => $z8]);
$dj["next-title"] = ay(
htmlspecialchars($z8["Title"], ENT_NOQUOTES, "UTF-8")
);
}
$dj["title"] = $_strings["nm--posts"];
$dj["timeline?"] = false;
$dj["this-title"] = ay(
htmlspecialchars($zy["Title"], ENT_NOQUOTES, "UTF-8")
);
if (Log::$a) {
__log("}");
}
if (Log::$a) {
__log("Comments {");
}
if ($gn) {
$k8 = e2_note_cache_filename_with_id_(
$zy["ID"] . "-comments-author"
);
} else {
$k8 = e2_note_cache_filename_with_id_($zy["ID"] . "-comments");
}
$x8 = null;