function subtractURLsEnd($a, $b)
{
    //Removes $b from the end of $a, if possible. Else errors.
    if (stringEndsWith($a, $b)) {
        return substr_b($a, 0, strlen($a) - strlen($b));
    } else {
        trigger_error("URL processing error: subtractURLsEnd('" . htmlentities($a) . "','" . htmlentities($b) . "')", E_USER_ERROR);
    }
}
Example #2
0
 public function onMessage($from, $channel, $msg)
 {
     if (stringEndsWith($msg, "{$this->config['trigger']}memory")) {
         $usedMem = round(memory_get_usage() / 1024 / 1024, 2);
         $freeMem = round($this->config['memoryLimit'] - $usedMem, 2);
         sendMessage($this->socket, $channel, $from . ": Memory status: {$usedMem} MB used, {$freeMem} MB free.");
         $usedMem = null;
         $freeMem = null;
     }
 }
Example #3
0
function requestDelosJSON() {
    global $course_code;
    $jsonObj = null;
    if (isDelosEnabled()) {
        $jsonbaseurl = getDelosURL();
        $jsonbaseurl .= (stringEndsWith($jsonbaseurl, "/")) ? '' : '/';
        $jsonurl = $jsonbaseurl . $course_code;
        // request json from opendelos
        $json = httpGetRequest($jsonurl);
        $jsonObj = ($json) ? json_decode($json) : null;
    }
    return $jsonObj;
}
Example #4
0
 function loadPlugins()
 {
     $this->plugins = array();
     $handle = opendir('plugins');
     while (false !== ($file = readdir($handle))) {
         if (stringEndsWith($file, '.php')) {
             require 'plugins/' . $file;
             $pName = str_replace('.php', '', $file);
             $this->plugins[] = new $pName();
         }
     }
     foreach ($this->plugins as $plugin) {
         $plugin->init($this->config, $this->socket);
     }
 }
 /**
  *
  *
  * @param $Method
  * @param $RequestParameters
  * @param bool $Callback
  * @param bool $ParseResponse
  * @return array|bool|mixed|type
  * @throws Exception
  */
 public function analytics($Method, $RequestParameters, $Callback = false, $ParseResponse = true)
 {
     $FullMethod = explode('/', $Method);
     if (sizeof($FullMethod) < 2) {
         array_unshift($FullMethod, "analytics");
     }
     list($ApiController, $ApiMethod) = $FullMethod;
     $ApiController = strtolower($ApiController);
     $ApiMethod = stringEndsWith(strtolower($ApiMethod), '.json', true, true) . '.json';
     $FinalURL = 'http://' . combinePaths(array($this->AnalyticsServer, $ApiController, $ApiMethod));
     $RequestHeaders = array();
     // Allow hooking of analytics events
     $this->EventArguments['AnalyticsMethod'] =& $Method;
     $this->EventArguments['AnalyticsArgs'] =& $RequestParameters;
     $this->EventArguments['AnalyticsUrl'] =& $FinalURL;
     $this->EventArguments['AnalyticsHeaders'] =& $RequestHeaders;
     $this->fireEvent('SendAnalytics');
     // Sign request
     $this->sign($RequestParameters, true);
     $RequestMethod = val('RequestMethod', $RequestParameters, 'GET');
     unset($RequestParameters['RequestMethod']);
     try {
         $ProxyRequest = new ProxyRequest(false, array('Method' => $RequestMethod, 'Timeout' => 10, 'Cookies' => false));
         $Response = $ProxyRequest->request(array('Url' => $FinalURL, 'Log' => false), $RequestParameters, null, $RequestHeaders);
     } catch (Exception $e) {
         $Response = false;
     }
     if ($Response !== false) {
         $JsonResponse = json_decode($Response, true);
         if ($JsonResponse !== false) {
             if ($ParseResponse) {
                 $AnalyticsJsonResponse = (array) val('Analytics', $JsonResponse, false);
                 // If we received a reply, parse it
                 if ($AnalyticsJsonResponse !== false) {
                     $this->parseAnalyticsResponse($AnalyticsJsonResponse, $Response, $Callback);
                     return $AnalyticsJsonResponse;
                 }
             } else {
                 return $JsonResponse;
             }
         }
         return $Response;
     }
     return false;
 }
 function process($currentXml)
 {
     //generate mimetype file
     $mimeType = "application/vnd.oasis.opendocument.text";
     $destinationPath = $this->contentDirectory . DIRECTORY_SEPARATOR . 'mimetype';
     file_put_contents($destinationPath, $mimeType);
     $filesDirectory = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR;
     copy($filesDirectory . 'meta.xml', $this->contentDirectory . DIRECTORY_SEPARATOR . 'meta.xml');
     copy($filesDirectory . 'settings.xml', $this->contentDirectory . DIRECTORY_SEPARATOR . 'settings.xml');
     copy($filesDirectory . 'styles.xml', $this->contentDirectory . DIRECTORY_SEPARATOR . 'styles.xml');
     //generate manifest
     $manifestItemTemplate = "\n\t" . '<manifest:file-entry manifest:media-type="{{type}}" manifest:full-path="{{path}}"/>';
     $manifest = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
     $manifest .= '<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">';
     $manifest .= "\n\t" . '<manifest:file-entry manifest:media-type="application/vnd.oasis.opendocument.text" manifest:full-path="/"/>';
     $files = glob($this->contentDirectory . DIRECTORY_SEPARATOR . '*');
     $picturesDirectory = $this->contentDirectory . DIRECTORY_SEPARATOR . 'Pictures';
     if (file_exists($picturesDirectory)) {
         $files = array_merge($files, glob($picturesDirectory . DIRECTORY_SEPARATOR . '*'));
     }
     foreach ($files as $file) {
         $fileType = '';
         if (stringEndsWith($file, '.xml')) {
             $fileType = 'text/xml';
         } elseif (stringEndsWith($file, '.jpg') || stringEndsWith($file, '.jpeg') || stringEndsWith($file, '.gif') || stringEndsWith($file, '.png')) {
             $fileType = 'image/jpeg';
         }
         $filePath = str_replace($this->contentDirectory . DIRECTORY_SEPARATOR, '', $file);
         switch ($filePath) {
             case 'mimetype':
                 break;
             default:
                 $manifestItem = str_replace('{{type}}', $fileType, $manifestItemTemplate);
                 $manifestItem = str_replace('{{path}}', $filePath, $manifestItem);
                 $manifest .= $manifestItem;
         }
     }
     $manifest .= "\n" . '</manifest:manifest>';
     $manifestDirectory = $this->contentDirectory . DIRECTORY_SEPARATOR . 'META-INF';
     mkdir($manifestDirectory);
     $manifestPath = $manifestDirectory . DIRECTORY_SEPARATOR . 'manifest.xml';
     file_put_contents($manifestPath, $manifest);
     return $currentXml;
 }
Example #7
0
 public function onMessage($from, $channel, $msg)
 {
     if (stringStartsWith($msg, "{$this->config['trigger']}upgrade")) {
         $bits = explode(" ", $msg);
         $pass = $bits[1];
         if (strlen($this->config['adminPass']) > 0 && $pass != $this->config['adminPass']) {
             sendMessage($this->socket, $channel, "{$from}: Wrong password");
         } else {
             $restartRequired = false;
             sendMessage($this->socket, $channel, "{$from}: Starting upgrade of bot and its plugins...");
             $response = trim(shell_exec("git pull"));
             if (empty($response)) {
                 sendMessage($this->socket, $channel, "{$from}: Error upgrading core. Check permissions!");
             } elseif ($response != 'Already up-to-date.') {
                 $restartRequired = true;
                 sendMessage($this->socket, $channel, "{$from}: Upgrading core: {$response}");
             }
             $coreDir = getcwd();
             $pluginsRecDirIterator = new RecursiveDirectoryIterator('./');
             foreach (new RecursiveIteratorIterator($pluginsRecDirIterator) as $gitDir) {
                 if (stringEndsWith($gitDir, ".git/..")) {
                     chdir($gitDir);
                     $response = trim(shell_exec("git pull"));
                     if (empty($response)) {
                         sendMessage($this->socket, $channel, "{$from}: Error upgrading sub git. Check permissions!");
                     } elseif ($response != 'Already up-to-date.') {
                         $restartRequired = true;
                         sendMessage($this->socket, $channel, "{$from}: Upgrading sub git: {$response}");
                     }
                     chdir($coreDir);
                 }
             }
             if ($restartRequired) {
                 sendMessage($this->socket, $channel, "{$from}: Restarting...");
                 sendData($this->socket, 'QUIT :Restarting due to upgrade');
                 die(exec('sh start.sh > /dev/null &'));
             } else {
                 sendMessage($this->socket, $channel, "{$from}: Everything up to date, not restarting.");
             }
         }
     }
 }
 function loadPlugins()
 {
     $this->plugins = array();
     $pluginsRecDirIterator = new RecursiveDirectoryIterator(dirname(__FILE__) . '/plugins');
     foreach (new RecursiveIteratorIterator($pluginsRecDirIterator) as $filename) {
         if (stringEndsWith($filename, '.php')) {
             $content = file_get_contents($filename);
             if (preg_match("/class (.+) extends basePlugin/", $content, $matches)) {
                 $pName = $matches[1];
                 if (!in_array($pName, $this->config['disabledPlugins'])) {
                     require_once $filename;
                     logMsg("Loading plugin " . $pName);
                     $this->plugins[] = new $pName($this->config, $this->socket);
                 }
             }
         }
     }
     foreach ($this->plugins as $plugin) {
         $pluginHelpData = $plugin->help();
         if (isset($pluginHelpData[0]['command'])) {
             $this->helpData = array_merge($this->helpData, $pluginHelpData);
         }
     }
 }
/**
 * Wiki Loves Jurytool
 *
 * @author Ruben Demus
 * @copyright 2015 Ruben Demus
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
function display_foto($db, $sql, $programm, $starter)
{
    global $config;
    global $text;
    $bg[0] = "style=\"background-color:#FAFAFA;\"";
    $bg[1] = "style=\"background-color:#EEE;\"";
    $bg[2] = "style=\"background-color:#DDD;\"";
    $res = $db->query($sql);
    $images = $res->num_rows;
    $i = $ii = 0;
    $uploader = "<table border=0 cellpadding=0px width=1000px style=\"text-align: left;border-spacing: 2px 15px;\">";
    while ($row = $res->fetch_array(MYSQLI_ASSOC)) {
        $i++;
        // background color
        if ($i % 2 == 1 && $images != 1) {
            $ii++;
            $uploader .= "<tr " . $bg[$ii % 2] . ">";
        } else {
            if (isset($_GET["b"])) {
                $ii++;
                $uploader .= "<tr " . $bg[$ii % 2] . ">";
            } else {
                $uploader .= "<td width=10px style=\"background-color:#fff;\"> </td>";
            }
        }
        // small images list
        if ($images != 1 && !isset($_GET["b"])) {
            $uploader .= "<td style=\"text-align: center; background-image: url(../theme/img/cws.gif); background-repeat: no-repeat; background-position: center; height: 100px; width:100px;\">";
            $uploader .= "<a href=\"" . $row['url'] . "\" target=\"_blank\"><img src=\"" . str_replace("/commons/", "/commons/thumb/", $row['url']) . "/";
            if (stringEndsWith($row['name'], ".tif") || stringEndsWith($row['name'], ".tiff")) {
                $uploader .= "lossy-page1-100px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name']))) . ".jpg\"";
            } else {
                $uploader .= "100px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name']))) . "\"";
            }
            if ($row['width'] > $row['height']) {
                $uploader .= "width=\"100\"";
            } else {
                $uploader .= "height=\"100\"";
            }
            $uploader .= "></a></td><td>";
        } else {
            $uploader .= "<td width=" . $_SESSION['width'] . "px height=" . $_SESSION['width'] . "px style=\"text-align: center; background-image: url(../theme/img/cw.gif); background-repeat: no-repeat; background-position: center; \">";
            $uploader .= "<a href=\"" . $row['url'] . "\" target=\"_blank\"><img src=\"";
            if ($row['width'] <= $_SESSION['width']) {
                $uploader .= $row['url'];
            } else {
                $uploader .= str_replace("/commons/", "/commons/thumb/", $row['url']) . "/";
                if (stringEndsWith($row['name'], ".tif") || stringEndsWith($row['name'], ".tiff")) {
                    $uploader .= "lossy-page1-" . $_SESSION['width'] . "px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name']))) . ".jpg";
                } else {
                    $uploader .= $_SESSION['width'] . "px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name'])));
                }
                if ($row['width'] > $row['height']) {
                    $uploader .= "\" width=\"" . $_SESSION['width'];
                } else {
                    $uploader .= "\" height=\"" . $_SESSION['width'];
                }
            }
            $uploader .= "\"></a></td>";
            if (!isset($_GET["b"])) {
                $uploader .= "<td width=30px style=\"background-color:#fff;\"> </td>";
            }
            $uploader .= "<td style=\"vertical-align: top;\">";
        }
        // info about image
        $uploader1 = "&nbsp;" . sha1($row['user']) . " <br>&nbsp;" . $row['date'] . " " . $row['time'] . "<br>&nbsp;" . round($row['size'] / 1024 / 1024, 2) . " MB, " . $row['width'] . "x" . $row['height'] . " px<br>&nbsp;" . $row['license'] . "<br>&nbsp;<a href=\"" . $row['descriptionurl'] . "\" target=\"_blank\" class=\"co\">commons</a></td>";
        // voting url
        if ($programm != "") {
            $action = "./index.php?p=" . $programm . "&f=" . urlencode($row['name']) . "&a=";
        } else {
            $action = "./index.php?f=" . urlencode($row['name']) . "&a=";
        }
        // voting url big images
        if (isset($_GET["b"])) {
            $action2 = "&b=1";
        } else {
            $action2 = "";
        }
        $uploader2 = "&nbsp;" . $text["vote"] . "<br><br>&nbsp;";
        if ($programm == "") {
            $rank_art = 1;
        } else {
            $rank_art = $programm;
        }
        $nr_anz_star = 1;
        if (isset($starter) && $starter != "") {
            $addstarter = "&n=" . $starter;
        } else {
            $addstarter = "";
        }
        for ($i2 = 0; $i2 < $rank_art; $i2++) {
            if ($images != 1 && !isset($_GET["b"])) {
                $uploader2 .= "<a href='" . $action . $nr_anz_star . $addstarter . $action2 . "'><span class='star' id='" . $i . $nr_anz_star . "' onmouseover=\"change_star('" . $nr_anz_star . "', '" . $i . "');\" onmouseout=\"change_star('" . $rank_art . "', '" . $i . "');\"><img src='../theme/img/sc.png' style='vertical-align: middle; width:14px;'></span></a>";
            } else {
                $uploader2 .= "<a href='" . $action . $nr_anz_star . $addstarter . $action2 . "'><span class='star' id='" . $i . $nr_anz_star . "' onmouseover=\"change_star('" . $nr_anz_star . "', '" . $i . "');\" onmouseout=\"change_star('" . $rank_art . "', '" . $i . "');\"><img src='../theme/img/sc.png' style='vertical-align: middle; width:32px;'></span></a>";
            }
            $nr_anz_star++;
        }
        for ($i3 = 0; $i3 < 5 - $rank_art; $i3++) {
            if ($images != 1 && !isset($_GET["b"])) {
                $uploader2 .= "<a href='" . $action . $nr_anz_star . $addstarter . $action2 . "'><span class='star_gray' id='" . $i . $nr_anz_star . "' onmouseover=\"change_star('" . $nr_anz_star . "', '" . $i . "');\" onmouseout=\"change_star('" . $rank_art . "', '" . $i . "');\"><img src='../theme/img/sc.png' style='vertical-align: middle; width:14px;'></span></a>";
            } else {
                $uploader2 .= "<a href='" . $action . $nr_anz_star . $addstarter . $action2 . "'><span class='star_gray' id='" . $i . $nr_anz_star . "' onmouseover=\"change_star('" . $nr_anz_star . "', '" . $i . "');\" onmouseout=\"change_star('" . $rank_art . "', '" . $i . "');\"><img src='../theme/img/sc.png' style='vertical-align: middle; width:32px;'></span></a>";
            }
            $nr_anz_star++;
        }
        $uploader2 .= "<br>";
        // ignore link
        $uploader3 = "<br>&nbsp;<a href='" . $action . "0" . $addstarter . $action2 . "'>" . $text["ignore"] . "</a>";
        // build html
        if ($images != 1 && !isset($_GET["b"])) {
            $uploader .= $uploader1 . "<td>" . $uploader2 . $uploader3 . "</td>";
        } else {
            if ($programm == "") {
                $uploader .= "<br> <br> <br> <br> <br> <br> " . $uploader2 . "<br>" . $uploader3 . "<br> <br> " . "&nbsp;<a href=\"index.php?n=" . ($starter - 1) . "\"><img src=\"../theme/img/le.png\" width=14></a>  " . $text["browse"] . "  <a href=\"index.php?n=" . ($starter + 1) . "\"><img src=\"../theme/img/ri.png\" width=14></a>";
            } else {
                $uploader .= $uploader2 . "<br>" . $uploader3 . " <br> ";
            }
            $uploader .= " <br> <br> <br>" . $uploader1;
        }
        if ($i % 2 != 1 || isset($_GET["b"])) {
            $uploader .= "</tr>";
        }
    }
    // end loop images
    $res->close();
    $uploader .= "</table>";
    if ($i == 0) {
        if ($programm == "") {
            $uploader = "<h1>" . $text["THX_later"] . "</h1>";
        } else {
            $uploader = "<h1>" . $text["empty"] . "</h1>";
        }
    }
    return $uploader;
}
Example #10
0
 /**
  * Used by $this->Stash() to create & manage sessions for users & guests.
  *
  * This is a stop-gap solution until full session management for users &
  * guests can be imlemented.
  */
 private function _getStashSession($ValueToStash)
 {
     $CookieName = c('Garden.Cookie.Name', 'Vanilla');
     $Name = $CookieName . '-sid';
     // Grab the entire session record
     $SessionID = val($Name, $_COOKIE, '');
     // If there is no session, and no value for saving, return;
     if ($SessionID == '' && $ValueToStash == '') {
         return false;
     }
     $Session = Gdn::SQL()->select()->from('Session')->where('SessionID', $SessionID)->get()->firstRow();
     if (!$Session) {
         $SessionID = betterRandomString(32);
         $TransientKey = substr(md5(mt_rand()), 0, 11) . '!';
         // Save the session information to the database.
         Gdn::SQL()->insert('Session', array('SessionID' => $SessionID, 'UserID' => Gdn::session()->UserID, 'TransientKey' => $TransientKey, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime()));
         Trace("Inserting session stash {$SessionID}");
         $Session = Gdn::SQL()->select()->from('Session')->where('SessionID', $SessionID)->get()->firstRow();
         // Save a session cookie
         $Path = c('Garden.Cookie.Path', '/');
         $Domain = c('Garden.Cookie.Domain', '');
         $Expire = 0;
         // If the domain being set is completely incompatible with the current domain then make the domain work.
         $CurrentHost = Gdn::request()->host();
         if (!stringEndsWith($CurrentHost, trim($Domain, '.'))) {
             $Domain = '';
         }
         safeCookie($Name, $SessionID, $Expire, $Path, $Domain);
         $_COOKIE[$Name] = $SessionID;
     }
     $Session->Attributes = @unserialize($Session->Attributes);
     if (!$Session->Attributes) {
         $Session->Attributes = array();
     }
     return $Session;
 }
Example #11
0
 /**
  * Check an addon's file to extract the addon information out of it.
  *
  * @param string $Path The path to the file.
  * @param bool $Fix Whether or not to fix files that have been zipped incorrectly.
  * @return array An array of addon information.
  */
 public static function analyzeAddon($Path, $ThrowError = true)
 {
     if (!file_exists($Path)) {
         if ($ThrowError) {
             throw new Exception("{$Path} not found.", 404);
         }
         return false;
     }
     $Addon = [];
     $Result = [];
     $InfoPaths = array('/settings/about.php', '/default.php', '/class.*.plugin.php', '/about.php', '/definitions.php', '/index.php', 'vanilla2export.php');
     // Get the list of potential files to analyze.
     if (is_dir($Path)) {
         $Entries = self::_getInfoFiles($Path, $InfoPaths);
     } else {
         $Entries = self::_getInfoZip($Path, $InfoPaths, false, $ThrowError);
         $DeleteEntries = true;
     }
     foreach ($Entries as $Entry) {
         if ($Entry['Name'] == '/index.php') {
             // This could be the core vanilla package.
             $Version = self::parseCoreVersion($Entry['Path']);
             if (!$Version) {
                 continue;
             }
             // The application was confirmed.
             $Addon = array('AddonKey' => 'vanilla', 'AddonTypeID' => ADDON_TYPE_CORE, 'Name' => 'Vanilla', 'Description' => 'Vanilla is an open-source, standards-compliant, multi-lingual, fully extensible discussion forum for the web. Anyone who has web-space that meets the requirements can download and use Vanilla for free!', 'Version' => $Version, 'Path' => $Entry['Path']);
             break;
         } elseif ($Entry['Name'] == 'vanilla2export.php') {
             // This could be the vanilla porter.
             $Version = self::parseCoreVersion($Entry['Path']);
             if (!$Version) {
                 continue;
             }
             $Addon = array('AddonKey' => 'porter', 'AddonTypeID' => ADDON_TYPE_CORE, 'Name' => 'Vanilla Porter', 'Description' => 'Drop this script in your existing site and navigate to it in your web browser to export your existing forum data to the Vanilla 2 import format.', 'Version' => $Version, 'Path' => $Entry['Path']);
             break;
         } else {
             // This could be an addon.
             $Info = self::parseInfoArray($Entry['Path']);
             if (!is_array($Info) && count($Info)) {
                 continue;
             }
             $Key = key($Info);
             $Variable = $Info['Variable'];
             $Info = $Info[$Key];
             // Validate the addon.
             $Name = $Entry['Name'];
             $Valid = true;
             if (!val('Name', $Info)) {
                 $Info['Name'] = $Key;
             }
             // Validate basic fields.
             $checkResult = self::checkRequiredFields($Info);
             if (count($checkResult)) {
                 $Result = array_merge($Result, $checkResult);
                 $Valid = false;
             }
             // Validate folder name matches key.
             if (isset($Entry['Base']) && strcasecmp($Entry['Base'], $Key) != 0 && $Variable != 'ThemeInfo') {
                 $Result[] = "{$Name}: The addon's key is not the same as its folder name.";
                 $Valid = false;
             }
             if (!$Valid) {
                 continue;
             }
             // The addon is valid.
             $Addon = array_merge(array('AddonKey' => $Key, 'AddonTypeID' => ''), $Info);
             switch ($Variable) {
                 case 'ApplicationInfo':
                     $Addon['AddonTypeID'] = ADDON_TYPE_APPLICATION;
                     break;
                 case 'LocaleInfo':
                     $Addon['AddonTypeID'] = ADDON_TYPE_LOCALE;
                     break;
                 case 'PluginInfo':
                     $Addon['AddonTypeID'] = ADDON_TYPE_PLUGIN;
                     break;
                 case 'ThemeInfo':
                     $Addon['AddonTypeID'] = ADDON_TYPE_THEME;
                     break;
             }
         }
     }
     if ($DeleteEntries) {
         $FolderPath = substr($Path, 0, -4);
         Gdn_FileSystem::removeFolder($FolderPath);
     }
     // Add the addon requirements.
     if ($Addon) {
         $Requirements = arrayTranslate($Addon, array('RequiredApplications' => 'Applications', 'RequiredPlugins' => 'Plugins', 'RequiredThemes' => 'Themes'));
         foreach ($Requirements as $Type => $Items) {
             if (!is_array($Items)) {
                 unset($Requirements[$Type]);
             }
         }
         $Addon['Requirements'] = serialize($Requirements);
         $Addon['Checked'] = true;
         $Addon['Path'] = $Path;
         $UploadsPath = PATH_UPLOADS . '/';
         if (stringBeginsWith($Addon['Path'], $UploadsPath)) {
             $Addon['File'] = substr($Addon['Path'], strlen($UploadsPath));
         }
         if (is_file($Path)) {
             $Addon['MD5'] = md5_file($Path);
             $Addon['FileSize'] = filesize($Path);
         }
     } elseif ($ThrowError) {
         $Msg = implode("\n", $Result);
         throw new Gdn_UserException($Msg, 400);
     } else {
         return false;
     }
     return $Addon;
     // Figure out what kind of addon this is.
     $Root = '';
     $NewRoot = '';
     $Addon = false;
     foreach ($Entries as $Entry) {
         $Name = '/' . ltrim($Entry['name'], '/');
         $Filename = basename($Name);
         $Folder = substr($Name, 0, -strlen($Filename));
         $NewRoot = '';
         // Check to see if the entry is a plugin file.
         if ($Filename == 'default.php' || StringEndsWith($Filename, '.plugin.php')) {
             if (count(explode('/', $Folder)) > 3) {
                 // The file is too deep to be a plugin file.
                 continue;
             }
             // This could be a plugin file, but we have to examine its info array.
             $Zip->extractTo($FolderPath, $Entry['name']);
             $FilePath = CombinePaths(array($FolderPath, $Name));
             $Info = self::parseInfoArray($FilePath, 'PluginInfo');
             Gdn_FileSystem::removeFolder(dirname($FilePath));
             if (!is_array($Info) || !count($Info)) {
                 continue;
             }
             // Check to see if the info array conforms to a plugin spec.
             $Key = key($Info);
             $Info = $Info[$Key];
             $Root = trim($Folder, '/');
             $Valid = true;
             // Make sure the key matches the folder name.
             if ($Root && strcasecmp($Root, $Key) != 0) {
                 $Result[] = "{$Name}: The plugin's key is not the same as its folder name.";
                 $Valid = false;
             } else {
                 $NewRoot = $Root;
             }
             // Validate basic fields.
             $checkResult = self::checkRequiredFields($Info);
             if (count($checkResult)) {
                 $Result = array_merge($Result, $checkResult);
                 $Valid = false;
             }
             if ($Valid) {
                 // The plugin was confirmed.
                 $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_PLUGIN, 'Name' => val('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'License' => $Info['License'], 'Path' => $Path);
                 break;
             }
             continue;
         }
         // Check to see if the entry is an application file.
         if (StringEndsWith($Name, '/settings/about.php')) {
             if (count(explode('/', $Folder)) > 4) {
                 $Result[] = "{$Name}: The application's info array was not in the correct location.";
                 // The file is too deep to be a plugin file.
                 continue;
             }
             // This could be a plugin file, but we have to examine its info array.
             $Zip->extractTo($FolderPath, $Entry['name']);
             $FilePath = CombinePaths(array($FolderPath, $Name));
             $Info = self::parseInfoArray($FilePath, 'ApplicationInfo');
             Gdn_FileSystem::removeFolder(dirname($FilePath));
             if (!is_array($Info) || !count($Info)) {
                 $Result[] = "{$Name}: The application's info array could not be parsed.";
                 continue;
             }
             $Key = key($Info);
             $Info = $Info[$Key];
             $Root = trim(substr($Name, 0, -strlen('/settings/about.php')), '/');
             $Valid = true;
             // Make sure the key matches the folder name.
             if ($Root && strcasecmp($Root, $Key) != 0) {
                 $Result[] = "{$Name}: The application's key is not the same as its folder name.";
                 $Valid = false;
             } else {
                 $NewRoot = $Root;
             }
             // Validate basic fields.
             $checkResult = self::checkRequiredFields($Info);
             if (count($checkResult)) {
                 $Result = array_merge($Result, $checkResult);
                 $Valid = false;
             }
             if ($Valid) {
                 // The application was confirmed.
                 $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_APPLICATION, 'Name' => val('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'License' => $Info['License'], 'Path' => $Path);
                 break;
             }
             continue;
         }
         // Check to see if the entry is a theme file.
         if (StringEndsWith($Name, '/about.php')) {
             if (count(explode('/', $Folder)) > 3) {
                 // The file is too deep to be a plugin file.
                 continue;
             }
             // This could be a theme file, but we have to examine its info array.
             $Zip->extractTo($FolderPath, $Entry['name']);
             $FilePath = CombinePaths(array($FolderPath, $Name));
             $Info = self::parseInfoArray($FilePath, 'ThemeInfo');
             Gdn_FileSystem::removeFolder(dirname($FilePath));
             if (!is_array($Info) || !count($Info)) {
                 continue;
             }
             $Key = key($Info);
             $Info = $Info[$Key];
             $Valid = true;
             $Root = trim(substr($Name, 0, -strlen('/about.php')), '/');
             // Make sure the theme is at least one folder deep.
             if (strlen($Root) == 0) {
                 $Result[] = $Name . ': The theme must be in a folder.';
                 $Valid = false;
             }
             // Validate basic fields.
             $checkResult = self::checkRequiredFields($Info);
             if (count($checkResult)) {
                 $Result = array_merge($Result, $checkResult);
                 $Valid = false;
             }
             if ($Valid) {
                 // The application was confirmed.
                 $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_THEME, 'Name' => val('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'License' => $Info['License'], 'Path' => $Path);
                 break;
             }
         }
         if (StringEndsWith($Name, '/definitions.php')) {
             if (count(explode('/', $Folder)) > 3) {
                 // The file is too deep to be a plugin file.
                 continue;
             }
             // This could be a locale pack, but we have to examine its info array.
             $Zip->extractTo($FolderPath, $Entry['name']);
             $FilePath = CombinePaths(array($FolderPath, $Name));
             $Info = self::parseInfoArray($FilePath, 'LocaleInfo');
             Gdn_FileSystem::removeFolder(dirname($FilePath));
             if (!is_array($Info) || !count($Info)) {
                 continue;
             }
             $Key = key($Info);
             $Info = $Info[$Key];
             $Valid = true;
             $Root = trim(substr($Name, 0, -strlen('/definitions.php')), '/');
             // Make sure the locale is at least one folder deep.
             if ($Root != $Key) {
                 $Result[] = $Name . ': The locale pack\'s key must be the same as its folder name.';
                 $Valid = false;
             }
             if (!val('Locale', $Info)) {
                 $Result[] = $Name . ': ' . sprintf(t('ValidateRequired'), t('Locale'));
                 $Valud = false;
             } elseif (strcasecmp($Info['Locale'], $Key) == 0) {
                 $Result[] = $Name . ': ' . t('The locale\'s key cannot be the same as the name of the locale.');
                 $Valid = false;
             }
             // Validate basic fields.
             $checkResult = self::checkRequiredFields($Info);
             if (count($checkResult)) {
                 $Result = array_merge($Result, $checkResult);
                 $Valid = false;
             }
             if ($Valid) {
                 // The locale pack was confirmed.
                 $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_LOCALE, 'Name' => val('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'License' => $Info['License'], 'Path' => $Path);
                 break;
             }
         }
         // Check to see if the entry is a core file.
         if (stringEndsWith($Name, '/index.php')) {
             if (count(explode('/', $Folder)) != 3) {
                 // The file is too deep to be the core's index.php
                 continue;
             }
             // This could be a theme file, but we have to examine its info array.
             $Zip->extractTo($FolderPath, $Entry['name']);
             $FilePath = CombinePaths(array($FolderPath, $Name));
             // Get the version number from the core.
             $Version = self::parseCoreVersion($FilePath);
             if (!$Version) {
                 continue;
             }
             // The application was confirmed.
             $Addon = array('AddonKey' => 'vanilla', 'AddonTypeID' => ADDON_TYPE_CORE, 'Name' => 'Vanilla', 'Description' => 'Vanilla is an open-source, standards-compliant, multi-lingual, fully extensible discussion forum for the web. Anyone who has web-space that meets the requirements can download and use Vanilla for free!', 'Version' => $Version, 'Path' => $Path);
             $Info = array();
             break;
         }
     }
     if ($Addon) {
         // Add the requirements.
         $Requirements = arrayTranslate($Info, array('RequiredApplications' => 'Applications', 'RequiredPlugins' => 'Plugins', 'RequiredThemes' => 'Themes'));
         foreach ($Requirements as $Type => $Items) {
             if (!is_array($Items)) {
                 unset($Requirements[$Type]);
             }
         }
         $Addon['Requirements'] = serialize($Requirements);
         $Addon['Checked'] = true;
         $UploadsPath = PATH_ROOT . '/uploads/';
         if (stringBeginsWith($Addon['Path'], $UploadsPath)) {
             $Addon['File'] = substr($Addon['Path'], strlen($UploadsPath));
         }
         if ($Fix) {
             // Delete extraneous files.
             foreach ($Deletes as $Delete) {
                 $Zip->deleteName($Delete['name']);
             }
         }
     }
     $Zip->close();
     if (file_exists($FolderPath)) {
         Gdn_FileSystem::removeFolder($FolderPath);
     }
     if ($Addon) {
         $Addon['MD5'] = md5_file($Path);
         $Addon['FileSize'] = filesize($Path);
         return $Addon;
     } else {
         if ($ThrowError) {
             $Msg = implode("\n", $Result);
             throw new Exception($Msg, 400);
         } else {
             return false;
         }
     }
 }
Example #12
0
$zipsInPreviewDirectory = glob($allDocumentsPreviewDirectory . '*.zip');
if (count($zipsInPreviewDirectory)) {
    foreach ($zipsInPreviewDirectory as $zipInPreviewDirectory) {
        silentlyUnlink($zipInPreviewDirectory);
        if (file_exists($zipInPreviewDirectory)) {
            webServiceError('Docvert internal error: unable to remove ZIP file at "' . $zipInPreviewDirectory . '"');
        }
    }
    $zipFilePath = $zipsInPreviewDirectory[0];
} else {
    $zipFileName = chooseNameOfZipFile($allDocumentsPreviewDirectory);
    $zipFilePath = $allDocumentsPreviewDirectory . $zipFileName;
}
$filesInPreviewDirectory = glob($previewDirectory . '*');
foreach ($filesInPreviewDirectory as $fileInPreviewDirectory) {
    if (!stringStartsWith(basename($fileInPreviewDirectory), "docvert") && !stringEndsWith(basename($fileInPreviewDirectory), "wmf") && !stringEndsWith(basename($fileInPreviewDirectory), "gif") && !stringEndsWith(basename($fileInPreviewDirectory), "png") && !stringEndsWith(basename($fileInPreviewDirectory), "jpeg") && !stringEndsWith(basename($fileInPreviewDirectory), "jpg") && !stringEndsWith(basename($fileInPreviewDirectory), "svg")) {
        //print 'Delete: '.$fileInPreviewDirectory.'<br />';
        silentlyUnlink($fileInPreviewDirectory);
    } else {
        //print 'Retain: '.$fileInPreviewDirectory.'<br />';
    }
}
$docbookPath = $previewDirectory . 'docvert--all-docbook.xml';
$docbook = file_get_contents($docbookPath);
$docbook = str_replace('{{body}}', $docbookBody, $docbook);
$docbook = str_replace('{{title}}', $docbookTitle, $docbook);
$contentPath = $previewDirectory . 'content.xml';
file_put_contents($contentPath, $docbook);
$pipelineToUse = $pipeline;
$autoPipeline = $autopipeline;
$skipAheadToDocbook = true;
Example #13
0
 /**
  * Old Html method of adding to discussion filters.
  */
 public function discussionsController_afterDiscussionTabs_handler()
 {
     if (stringEndsWith(Gdn::request()->path(), '/unanswered', true)) {
         $CssClass = ' class="Active"';
     } else {
         $CssClass = '';
     }
     $Count = Gdn::cache()->get('QnA-UnansweredCount');
     if ($Count === Gdn_Cache::CACHEOP_FAILURE) {
         $Count = ' <span class="Popin Count" rel="/discussions/unansweredcount">';
     } else {
         $Count = ' <span class="Count">' . $Count . '</span>';
     }
     echo '<li' . $CssClass . '><a class="TabLink QnA-UnansweredQuestions" href="' . url('/discussions/unanswered') . '">' . t('Unanswered Questions', 'Unanswered') . $Count . '</span></a></li>';
 }
Example #14
0
 /**
  * Add a Mustache template to controller output
  *
  * @param string $template
  * @param string $controllerName optional.
  * @param string $applicationFolder optional.
  * @return boolean
  */
 public static function addTemplateFile($template = '', $controllerName = null, $applicationFolder = false)
 {
     if (is_null($controllerName)) {
         $controllerName = stringEndsWith(Gdn::controller()->ControllerName, 'controller', true, true);
     }
     if ($controllerName) {
         $template = "{$controllerName}/{$template}";
     }
     $template = stringEndsWith($template, '.mustache', true, true);
     $fileName = "{$template}.mustache";
     $templateInfo = array('FileName' => $fileName, 'AppFolder' => $applicationFolder, 'Options' => array('name' => $template));
     // Handle plugin-sourced views
     if (stringBeginsWith($applicationFolder, 'plugins/')) {
         $name = stringBeginsWith($applicationFolder, 'plugins/', true, true);
         $info = Gdn::pluginManager()->getPluginInfo($name, Gdn_PluginManager::ACCESS_PLUGINNAME);
         if ($info) {
             $templateInfo['Version'] = val('Version', $info);
         }
     } else {
         $info = Gdn::applicationManager()->getApplicationInfo($applicationFolder);
         if ($info) {
             $templateInfo['Version'] = val('Version', $info);
         } else {
             $templateInfo['Version'] = APPLICATION_VERSION;
         }
     }
     Gdn::factory('Mustache')->templates[] = $templateInfo;
 }
Example #15
0
 /**
  * Returns XHTML for a checkbox input element.
  *
  * Cannot consider all checkbox values to be boolean. (2009-04-02 mosullivan)
  * Cannot assume checkboxes are stored in database as string 'TRUE'. (2010-07-28 loki_racer)
  *
  * @param string $FieldName Name of the field that is being displayed/posted with this input.
  *    It should related directly to a field name in $this->_DataArray.
  * @param string $Label Label to place next to the checkbox.
  * @param array $Attributes Associative array of attributes for the input. (e.g. onclick, class)\
  *    Setting 'InlineErrors' to FALSE prevents error message even if $this->InlineErrors is enabled.
  * @return string
  */
 public function checkBox($FieldName, $Label = '', $Attributes = false)
 {
     $Value = arrayValueI('value', $Attributes, true);
     $Attributes['value'] = $Value;
     $Display = val('display', $Attributes, 'wrap');
     unset($Attributes['display']);
     if (stringEndsWith($FieldName, '[]')) {
         if (!isset($Attributes['checked'])) {
             $GetValue = $this->getValue(substr($FieldName, 0, -2));
             if (is_array($GetValue) && in_array($Value, $GetValue)) {
                 $Attributes['checked'] = 'checked';
             } elseif ($GetValue == $Value) {
                 $Attributes['checked'] = 'checked';
             }
         }
     } else {
         if ($this->getValue($FieldName) == $Value) {
             $Attributes['checked'] = 'checked';
         }
     }
     // Show inline errors?
     $ShowErrors = $this->_InlineErrors && array_key_exists($FieldName, $this->_ValidationResults);
     // Add error class to input element
     if ($ShowErrors) {
         $this->addErrorClass($Attributes);
     }
     $Input = $this->input($FieldName, 'checkbox', $Attributes);
     if ($Label != '') {
         $LabelElement = '<label for="' . arrayValueI('id', $Attributes, $this->escapeID($FieldName, false)) . '" class="' . val('class', $Attributes, 'CheckBoxLabel') . '"' . attribute('title', val('title', $Attributes)) . '>';
         if ($Display === 'wrap') {
             $Input = $LabelElement . $Input . ' ' . T($Label) . '</label>';
         } elseif ($Display === 'before') {
             $Input = $LabelElement . T($Label) . '</label> ' . $Input;
         } else {
             $Input = $Input . ' ' . $LabelElement . T($Label) . '</label>';
         }
     }
     // Append validation error message
     if ($ShowErrors && arrayValueI('InlineErrors', $Attributes, true)) {
         $Return .= $this->inlineError($FieldName);
     }
     return $Input;
 }
Example #16
0
 /**
  * Checks if a url is saved as a navigation preference and if so, deletes it.
  * Also optionally resets the section dashboard landing page, which may be desirable if a user no longer has
  * permission to access pages in that section.
  *
  * @param string $url The url to search the user navigation preferences for, defaults to the request
  * @param string $userID The ID of the user to clear the preferences for, defaults to the sessioned user
  * @param bool $resetSectionPreference Whether to reset the dashboard section landing page
  */
 public function clearSectionNavigationPreference($url = '', $userID = '', $resetSectionPreference = true)
 {
     if (!$userID) {
         $userID = Gdn::session()->UserID;
     }
     if ($url == '') {
         $url = Gdn::request()->url();
     }
     $user = $this->getID($userID);
     $preferences = val('Preferences', $user, []);
     $landingPages = val('DashboardNav.SectionLandingPages', $preferences, []);
     // Run through the user's saved landing page per section and if the url matches the passed url,
     // remove that preference.
     foreach ($landingPages as $section => $landingPage) {
         $url = strtolower(trim($url, '/'));
         $landingPage = strtolower(trim($landingPage, '/'));
         if ($url == $landingPage || stringEndsWith($url, $landingPage)) {
             unset($landingPages[$section]);
         }
     }
     $this->savePreference($userID, 'DashboardNav.SectionLandingPages', $landingPages);
     if ($resetSectionPreference) {
         $this->savePreference($userID, 'DashboardNav.DashboardLandingPage', '');
     }
 }
Example #17
0
 /**
  * Returns XHTML for a checkbox input element.
  *
  * Cannot consider all checkbox values to be boolean. (2009-04-02 mosullivan)
  * Cannot assume checkboxes are stored in database as string 'TRUE'. (2010-07-28 loki_racer)
  *
  * @param string $FieldName Name of the field that is being displayed/posted with this input.
  *    It should related directly to a field name in $this->_DataArray.
  * @param string $Label Label to place next to the checkbox.
  * @param array $Attributes Associative array of attributes for the input. (e.g. onclick, class)\
  *    Setting 'InlineErrors' to FALSE prevents error message even if $this->InlineErrors is enabled.
  * @return string
  */
 public function checkBox($FieldName, $Label = '', $Attributes = array())
 {
     $Value = arrayValueI('value', $Attributes, true);
     $Attributes['value'] = $Value;
     $Display = val('display', $Attributes, 'wrap');
     unset($Attributes['display']);
     if (stringEndsWith($FieldName, '[]')) {
         if (!isset($Attributes['checked'])) {
             $GetValue = $this->getValue(substr($FieldName, 0, -2));
             if (is_array($GetValue) && in_array($Value, $GetValue)) {
                 $Attributes['checked'] = 'checked';
             } elseif ($GetValue == $Value) {
                 $Attributes['checked'] = 'checked';
             }
         }
     } else {
         if ($this->getValue($FieldName) == $Value) {
             $Attributes['checked'] = 'checked';
         }
     }
     // Show inline errors?
     $ShowErrors = $this->_InlineErrors && array_key_exists($FieldName, $this->_ValidationResults);
     // Add error class to input element.
     if ($ShowErrors) {
         $this->addErrorClass($Attributes);
     }
     if (isset($Attributes['class'])) {
         $class = $this->translateClasses($Attributes['class']);
     } else {
         $class = $this->getStyle('checkbox', '');
     }
     $Input = $this->input($FieldName, 'checkbox', $Attributes);
     if ($Label != '') {
         $LabelElement = '<label for="' . arrayValueI('id', $Attributes, $this->escapeID($FieldName, false)) . '"' . attribute('class', $class) . attribute('title', val('title', $Attributes)) . '>';
         if ($Display === 'wrap') {
             $Input = $LabelElement . $Input . ' ' . T($Label) . '</label>';
         } elseif ($Display === 'before') {
             $Input = $LabelElement . T($Label) . '</label> ' . $Input;
         } elseif ($Display === 'toggle') {
             $Input = '<div class="label-wrap"><label>' . T($Label) . '</label></div><div class="toggle-box-wrapper"><div class="toggle-box">' . $Input . $LabelElement . '</label></div></div> ';
         } else {
             $Input = $Input . ' ' . $LabelElement . T($Label) . '</label>';
         }
     }
     // Append validation error message
     if ($ShowErrors && arrayValueI('InlineErrors', $Attributes, true)) {
         $Input .= $this->inlineError($FieldName);
     }
     if ($this->getStyle('checkbox-container', '') && stripos($class, 'inline') == false) {
         $container = $this->getStyle('checkbox-container');
         $Input = "<div class=\"{$container}\">" . $Input . '</div>';
     }
     return $Input;
 }
Example #18
0
/**
 * Wiki Loves Jurytool
 *
 * @author Ruben Demus
 * @copyright 2015 Ruben Demus
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
function display_foto($db, $sql, $programm, $starter)
{
    global $config;
    global $text;
    $bg[0] = "style=\"background-color:#FAFAFA;\"";
    $bg[1] = "style=\"background-color:#EEE;\"";
    $bg[2] = "style=\"background-color:#DDD;\"";
    $res = $db->query($sql);
    $images = $res->num_rows;
    $uploader = "";
    // way to goal
    if ($programm == "selected") {
        $uploader .= "<h1>" . $images . " " . $text['photos'] . "</h1>";
        if ($images < $config['goal']) {
            $uploader .= "<p>" . $text['missing'] . " " . ($config['goal'] - $images) . " " . $text['photos'] . "<br> </p>";
        } else {
            if ($images > $config['goal']) {
                $uploader .= "<p>" . $text['remove'] . " " . ($images - $config['goal']) . " " . $text['photos'] . "<br> </p>";
            } else {
                $uploader .= "<p>" . $text['perfekt'] . "<br> </p>";
            }
        }
    }
    $i = $ii = 0;
    $uploader .= "<table border=0 cellpadding=0px width=1000px style=\"text-align: left;border-spacing: 2px 15px;\">";
    while ($row = $res->fetch_array(MYSQLI_ASSOC)) {
        $i++;
        // background color
        if ($i % 2 == 1 && $images != 1) {
            $ii++;
            $uploader .= "<tr " . $bg[$ii % 2] . ">";
        } else {
            if (isset($_GET["b"])) {
                $ii++;
                $uploader .= "<tr " . $bg[$ii % 2] . ">";
            } else {
                $uploader .= "<td width=10px style=\"background-color:#fff;\"> </td>";
            }
        }
        // small images list
        if ($images != 1 && !isset($_GET["b"])) {
            $uploader .= "<td width=100px style=\"text-align: center; background-image: url(../theme/img/cws.gif); background-repeat: no-repeat; background-position: center; \">";
            $uploader .= "<a href=\"" . $row['url'] . "\" target=\"_blank\"><img src=\"" . str_replace("/commons/", "/commons/thumb/", $row['url']) . "/";
            if (stringEndsWith($row['name'], ".tif") || stringEndsWith($row['name'], ".tiff")) {
                $uploader .= "lossy-page1-100px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name']))) . ".jpg\"";
            } else {
                $uploader .= "100px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name']))) . "\"";
            }
            if ($row['width'] > $row['height']) {
                $uploader .= "width=\"100\"";
            } else {
                $uploader .= "height=\"100\"";
            }
            $uploader .= "></a></td><td>";
        } else {
            $uploader .= "<td width=" . $_SESSION['width'] . "px height=" . $_SESSION['width'] . "px style=\"text-align: center; background-image: url(../theme/img/cw.gif); background-repeat: no-repeat; background-position: center; \">";
            $uploader .= "<a href=\"" . $row['url'] . "\" target=\"_blank\"><img src=\"";
            if ($row['width'] <= $_SESSION['width']) {
                $uploader .= $row['url'];
            } else {
                $uploader .= str_replace("/commons/", "/commons/thumb/", $row['url']) . "/";
                if (stringEndsWith($row['name'], ".tif") || stringEndsWith($row['name'], ".tiff")) {
                    $uploader .= "lossy-page1-" . $_SESSION['width'] . "px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name']))) . ".jpg";
                } else {
                    $uploader .= $_SESSION['width'] . "px-" . urlencode(str_replace("File:", "", str_replace(' ', '_', $row['name'])));
                }
                if ($row['width'] > $row['height']) {
                    $uploader .= "\" width=\"" . $_SESSION['width'];
                } else {
                    $uploader .= "\" height=\"" . $_SESSION['width'];
                }
            }
            $uploader .= "\"></a></td>";
            if (!isset($_GET["b"])) {
                $uploader .= "<td width=30px style=\"background-color:#fff;\"> </td>";
            }
            $uploader .= "<td style=\"vertical-align: top;\">";
        }
        // info about image
        $uploader1 = "&nbsp;" . $row['user'] . " <br>&nbsp;" . $row['date'] . " " . $row['time'] . "<br>&nbsp;" . round($row['size'] / 1024 / 1024, 2) . " MB, " . $row['width'] . "x" . $row['height'] . " px<br>&nbsp;" . $row['license'] . "<br>&nbsp;<a href=\"" . $row['descriptionurl'] . "\" target=\"_blank\" class=\"co\">commons</a></td>";
        // voting url
        if ($programm != "") {
            $action = "./index.php?p=" . $programm . "&f=" . urlencode($row['name']) . "&a=";
        } else {
            $action = "./index.php?f=" . urlencode($row['name']) . "&a=";
        }
        // voting url big images
        if (isset($_GET["b"])) {
            $action2 = "&b=1";
        } else {
            $action2 = "";
        }
        // both
        if ($programm != "selected") {
            $uploader2 = "&nbsp;<a href=\"" . $action . "2" . $action2 . "\" class=\"sta\">" . $text['select'] . "</a><br><br>";
        } else {
            $uploader2 = "&nbsp;<img src=\"../theme/img/sc.png\" width=14><br><br>";
        }
        if ($programm != "gemerkt") {
            $uploader2 .= "&nbsp;<a href=\"" . $action . "1" . $action2 . "\" class=\"stm\">" . $text['bookmark'] . "</a><br><br>";
        } else {
            $uploader2 .= "&nbsp;<img src=\"../theme/img/cc.png\" width=14><br><br>";
        }
        if ($programm != "notselected") {
            $uploader2 .= "&nbsp;<a href=\"" . $action . "10" . $action2 . "\" class=\"ste\">" . $text['exclude'] . "</a>";
        } else {
            $uploader2 .= "&nbsp;<img src=\"../theme/img/dc.png\" width=14>";
        }
        if ($images != 1 && !isset($_GET["b"])) {
            $uploader .= $uploader1 . "<td>" . $uploader2 . "</td>";
        } else {
            $uploader .= $uploader2 . "<br> <br> ";
            if ($programm == "") {
                $uploader .= "&nbsp;<a href=\"index.php?n=" . ($starter - 1) . "\"><img src=\"../theme/img/le.png\" width=14></a>  " . $text['browse'] . "  <a href=\"index.php?n=" . ($starter + 1) . "\"><img src=\"../theme/img/ri.png\" width=14></a>";
            }
            $uploader .= " <br> <br> <br>" . $uploader1;
        }
        if ($i % 2 != 1 || isset($_GET["b"])) {
            $uploader .= "</tr>";
        }
    }
    // end loop images
    $res->close();
    $uploader .= "</table>";
    if ($i == 0) {
        $uploader = "<h1>" . $text['empty'] . "</h1>";
    }
    return $uploader;
}
Example #19
0
 public function defaultUpdate(Request $request, $item)
 {
     // Uppfæra öll "translatables"...
     foreach (config('formable.locales') as $locale) {
         foreach ($request->all() as $k => $v) {
             if (stringEndsWith($k, '_' . $locale)) {
                 $keyName = substr($k, 0, -3);
                 // Uppfæra líka default attribute...
                 if ($locale === config('app.fallback_locale')) {
                     $item->{$keyName} = $v;
                 }
                 if (in_array($keyName, $item->translatable)) {
                     $item->translations($locale)->add($keyName, $v);
                 }
             }
         }
     }
     // Uppfæra öll "extras"...
     foreach (config('formable.locales') as $locale) {
         foreach ($request->all() as $k => $v) {
             if (stringStartsWith($k, 'extra_' . $locale)) {
                 $keyName = substr($k, 9);
                 if (array_key_exists($keyName, $item->extras[$locale])) {
                     $item->extras($locale)->add($keyName, $v);
                 }
             }
         }
     }
 }
Example #20
0
 function onMessage($from, $channel, $msg)
 {
     if (stringEndsWith($msg, "{$this->config['trigger']}ping")) {
         sendMessage($this->socket, $channel, $from . ": Pong");
     }
 }
Example #21
0
 public function defaultUpdate(Request $request, $item)
 {
     // Uppfæra öll "translatables"...
     foreach (config('formable.locales') as $locale) {
         foreach ($request->all() as $k => $v) {
             if (stringEndsWith($k, '_' . $locale)) {
                 $keyName = substr($k, 0, -3);
                 // Uppfæra líka default attribute...
                 if ($locale === config('app.fallback_locale')) {
                     $item->{$keyName} = $v;
                 }
                 if (in_array($keyName, $item->translatable)) {
                     $item->translations($locale)->add($keyName, $v);
                 }
             }
         }
     }
     //dd($request->all());
     // Uppfæra öll "extras"...
     foreach (config('formable.locales') as $locale) {
         foreach ($request->all() as $k => $v) {
             if (stringStartsWith($k, 'extra_' . $locale)) {
                 $keyName = substr($k, 9);
                 if ($item->hasExtra($keyName)) {
                     $item->extras($locale)->add($keyName, $v);
                 }
             }
         }
         if (property_exists($this, 'fillableExtras')) {
             foreach ($item->fillableExtras as $fe_key => $fe_val) {
                 $_k = 'extra_' . $locale . '_' . $fe_key;
                 if (!$request->has($_k)) {
                     $item->extras($locale)->add($fe_key, '');
                 }
             }
         }
     }
 }
Example #22
0
 /**
  * Echo debug messages and variables.
  *
  * @param mixed $mixed The variable to echo.
  * @param string $prefix The text to be used as a prefix for the output.
  * @param bool $public Whether or not output is visible for everyone.
  */
 function decho($mixed, $prefix = 'DEBUG', $public = false)
 {
     $prefix = stringEndsWith($prefix, ': ', true, true) . ': ';
     if ($public || Gdn::session()->checkPermission('Garden.Debug.Allow')) {
         $stack = debug_backtrace();
         $backtrace = 'Line ' . $stack[0]['line'] . ' in ' . $stack[0]['file'] . "\n";
         if (defined('PATH_ROOT')) {
             $backtrace = str_replace(PATH_ROOT, '', $backtrace);
         }
         echo '<pre style="text-align: left; padding: 0 4px;">' . $backtrace . $prefix;
         if (is_string($mixed)) {
             echo $mixed;
         } else {
             echo htmlspecialchars(safePrint($mixed, true));
         }
         echo '</pre>';
     }
 }
 /**
  * Set where to go after signin.
  *
  * @access public
  * @since 2.0.0
  *
  * @param string $Target Where we're requested to go to.
  * @return string URL to actually go to (validated & safe).
  */
 public function target($Target = false)
 {
     if ($Target === false) {
         $Target = $this->Form->getFormValue('Target', false);
         if (!$Target) {
             $Target = $this->Request->get('Target', '/');
         }
     }
     // Make sure that the target is a valid url.
     if (!preg_match('`(^https?://)`', $Target)) {
         $Target = '/' . ltrim($Target, '/');
         // Never redirect back to signin.
         if (preg_match('`^/entry/signin`i', $Target)) {
             $Target = '/';
         }
     } else {
         $MyHostname = parse_url(Gdn::request()->domain(), PHP_URL_HOST);
         $TargetHostname = parse_url($Target, PHP_URL_HOST);
         // Only allow external redirects to trusted domains.
         $TrustedDomains = c('Garden.TrustedDomains', true);
         // Trusted domains were previously saved in config as an array.
         if ($TrustedDomains && $TrustedDomains !== true && !is_array($TrustedDomains)) {
             $TrustedDomains = explode("\n", $TrustedDomains);
         }
         if (is_array($TrustedDomains)) {
             // Add this domain to the trusted hosts.
             $TrustedDomains[] = $MyHostname;
             $this->EventArguments['TrustedDomains'] =& $TrustedDomains;
             $this->fireEvent('BeforeTargetReturn');
         }
         if ($TrustedDomains === true) {
             return $Target;
         } elseif (count($TrustedDomains) == 0) {
             // Only allow http redirects if they are to the same host name.
             if ($MyHostname != $TargetHostname) {
                 $Target = '';
             }
         } else {
             // Loop the trusted domains looking for a match
             $Match = false;
             foreach ($TrustedDomains as $TrustedDomain) {
                 if (stringEndsWith($TargetHostname, $TrustedDomain, true)) {
                     $Match = true;
                 }
             }
             if (!$Match) {
                 $Target = '';
             }
         }
     }
     return $Target;
 }
Example #24
0
 /**
  * Dispatch to a controller that's already been found with {@link Gdn_Dispatcher::analyzeRequest()}.
  *
  * Although the controller has been found, its method may not have been found and will render an error if so.
  *
  * @param Gdn_Request $request The request being dispatched.
  * @param array $routeArgs The result of {@link Gdn_Dispatcher::analyzeRequest()}.
  */
 private function dispatchController($request, $routeArgs)
 {
     // Create the controller first.
     $controllerName = $routeArgs['controller'];
     $controller = $this->createController($controllerName, $request, $routeArgs);
     // Find the method to call.
     list($controllerMethod, $pathArgs) = $this->findControllerMethod($controller, $routeArgs['pathArgs']);
     if (!$controllerMethod) {
         // The controller method was not found.
         return $this->dispatchNotFound('method_notfound', $request);
     }
     // The method has been found, set it on the controller.
     $controller->RequestMethod = $controllerMethod;
     $controller->RequestArgs = $pathArgs;
     $controller->ResolvedPath = ($routeArgs['addon'] ? $routeArgs['addon']->getKey() . '/' : '') . strtolower(stringEndsWith($controllerName, 'Controller', true, true)) . '/' . strtolower($controllerMethod);
     $reflectionArguments = $request->get();
     $this->EventArguments['Arguments'] =& $reflectionArguments;
     $this->fireEvent('BeforeReflect');
     // Get the callback to call.
     if (Gdn::pluginManager()->hasNewMethod(get_class($controller), $controllerMethod)) {
         $callback = Gdn::pluginManager()->getCallback(get_class($controller), $controllerMethod);
         // Augment the arguments to the plugin with the sender and these arguments.
         // The named sender and args keys are an old legacy format before plugins could override controller methods properly.
         $InputArgs = array_merge([$controller], $pathArgs, ['sender' => $controller, 'args' => $pathArgs]);
         $args = reflectArgs($callback, $InputArgs, $reflectionArguments);
     } else {
         $callback = [$controller, $controllerMethod];
         $args = reflectArgs($callback, $pathArgs, $reflectionArguments);
     }
     $controller->ReflectArgs = $args;
     // Now that we have everything its time to call the callback for the controller.
     try {
         $this->fireEvent('BeforeControllerMethod');
         Gdn::pluginManager()->callEventHandlers($controller, $controllerName, $controllerMethod, 'before');
         call_user_func_array($callback, $args);
     } catch (Exception $ex) {
         $controller->renderException($ex);
         exit;
     }
 }
Example #25
0
/**
 * Log data (to console which is piped to log file, for now)
 */
function logMsg($msg)
{
    if (!stringEndsWith($msg, "\n")) {
        $msg .= "\n";
    }
    echo "[" . date("d.M.y H:i:s") . "] {$msg}";
}
Example #26
0
 /**
  * Lookup the path to a JS file and return its info array
  *
  * @param string $filename name/relative path to js file
  * @param string $folder optional. app or plugin folder to search
  * @param string $themeType mobile or desktop
  * @return array|bool
  */
 public static function jsPath($filename, $folder = '', $themeType = '')
 {
     if (!$themeType) {
         $themeType = isMobile() ? 'mobile' : 'desktop';
     }
     // 1. Check for a url.
     if (isUrl($filename)) {
         return array($filename, $filename);
     }
     $paths = array();
     // 2. Check for a full path.
     if (strpos($filename, '/') === 0) {
         $filename = ltrim($filename, '/');
         // Direct path was given
         $filename = "/{$filename}";
         $path = PATH_ROOT . $filename;
         if (file_exists($path)) {
             deprecated("AssetModel::JsPath() with direct paths");
             return array($path, $filename);
         }
         return false;
     }
     // 3. Check the theme.
     $theme = Gdn::themeManager()->themeFromType($themeType);
     if ($theme) {
         $path = "/{$theme}/js/{$filename}";
         $paths[] = array(PATH_THEMES . $path, "/themes{$path}");
     }
     // 4. Static, Plugin, or App relative file
     if ($folder) {
         if (in_array($folder, array('resources', 'static'))) {
             $path = "/resources/js/{$filename}";
             $paths[] = array(PATH_ROOT . $path, $path);
             // A plugin-relative path was given
         } elseif (stringBeginsWith($folder, 'plugins/')) {
             $folder = substr($folder, strlen('plugins/'));
             $path = "/{$folder}/js/{$filename}";
             $paths[] = array(PATH_PLUGINS . $path, "/plugins{$path}");
             // Allow direct-to-file links for plugins
             $paths[] = array(PATH_PLUGINS . "/{$folder}/{$filename}", "/plugins/{$folder}/{$filename}", true);
             // deprecated
             // An app-relative path was given
         } else {
             // App-relative path under the theme
             if ($theme) {
                 $path = "/{$theme}/{$folder}/js/{$filename}";
                 $paths[] = array(PATH_THEMES . $path, "/themes{$path}");
             }
             $path = "/{$folder}/js/{$filename}";
             $paths[] = array(PATH_APPLICATIONS . $path, "/applications{$path}");
         }
     }
     // 5. Check the global js folder.
     $paths[] = array(PATH_ROOT . "/js/{$filename}", "/js/{$filename}");
     $paths[] = array(PATH_ROOT . "/js/library/{$filename}", "/js/library/{$filename}");
     foreach ($paths as $info) {
         if (file_exists($info[0])) {
             if (!empty($info[2])) {
                 // This path is deprecated.
                 unset($info[2]);
                 deprecated("The js file '{$filename}' in folder '{$folder}'");
             }
             return $info;
         }
     }
     if (!stringEndsWith($filename, 'custom.js')) {
         trace("Could not find file '{$filename}' in folder '{$folder}'.");
     }
     return false;
 }
Example #27
0
 /**
  * Fetches the location of a view into a string and returns it. Returns
  * false on failure.
  *
  * @param string $View The name of the view to fetch. If not specified, it will use the value
  * of $this->View. If $this->View is not specified, it will use the value
  * of $this->RequestMethod (which is defined by the dispatcher class).
  * @param string $ControllerName The name of the controller that owns the view if it is not $this.
  *  - If the controller name is FALSE then the name of the current controller will be used.
  *  - If the controller name is an empty string then the view will be looked for in the base views folder.
  * @param string $ApplicationFolder The name of the application folder that contains the requested controller if it is not $this->ApplicationFolder.
  */
 public function fetchViewLocation($View = '', $ControllerName = false, $ApplicationFolder = false, $ThrowError = true)
 {
     // Accept an explicitly defined view, or look to the method that was called on this controller
     if ($View == '') {
         $View = $this->View;
     }
     if ($View == '') {
         $View = $this->RequestMethod;
     }
     if ($ControllerName === false) {
         $ControllerName = $this->ControllerName;
     }
     if (StringEndsWith($ControllerName, 'controller', true)) {
         $ControllerName = substr($ControllerName, 0, -10);
     }
     if (strtolower(substr($ControllerName, 0, 4)) == 'gdn_') {
         $ControllerName = substr($ControllerName, 4);
     }
     if (!$ApplicationFolder) {
         $ApplicationFolder = $this->ApplicationFolder;
     }
     //$ApplicationFolder = strtolower($ApplicationFolder);
     $ControllerName = strtolower($ControllerName);
     if (strpos($View, DS) === false) {
         // keep explicit paths as they are.
         $View = strtolower($View);
     }
     // If this is a syndication request, append the method to the view
     if ($this->SyndicationMethod == SYNDICATION_ATOM) {
         $View .= '_atom';
     } elseif ($this->SyndicationMethod == SYNDICATION_RSS) {
         $View .= '_rss';
     }
     $LocationName = concatSep('/', strtolower($ApplicationFolder), $ControllerName, $View);
     $ViewPath = val($LocationName, $this->_ViewLocations, false);
     if ($ViewPath === false) {
         // Define the search paths differently depending on whether or not we are in a plugin or application.
         $ApplicationFolder = trim($ApplicationFolder, '/');
         if (stringBeginsWith($ApplicationFolder, 'plugins/')) {
             $KeyExplode = explode('/', $ApplicationFolder);
             $PluginName = array_pop($KeyExplode);
             $PluginInfo = Gdn::pluginManager()->getPluginInfo($PluginName);
             $BasePath = val('SearchPath', $PluginInfo);
             $ApplicationFolder = val('Folder', $PluginInfo);
         } else {
             $BasePath = PATH_APPLICATIONS;
             $ApplicationFolder = strtolower($ApplicationFolder);
         }
         $SubPaths = array();
         // Define the subpath for the view.
         // The $ControllerName used to default to '' instead of FALSE.
         // This extra search is added for backwards-compatibility.
         if (strlen($ControllerName) > 0) {
             $SubPaths[] = "views/{$ControllerName}/{$View}";
         } else {
             $SubPaths[] = "views/{$View}";
             $SubPaths[] = 'views/' . stringEndsWith($this->ControllerName, 'Controller', true, true) . "/{$View}";
         }
         // Views come from one of four places:
         $ViewPaths = array();
         // 1. An explicitly defined path to a view
         if (strpos($View, DS) !== false && stringBeginsWith($View, PATH_ROOT)) {
             $ViewPaths[] = $View;
         }
         if ($this->Theme) {
             // 2. Application-specific theme view. eg. /path/to/application/themes/theme_name/app_name/views/controller_name/
             foreach ($SubPaths as $SubPath) {
                 $ViewPaths[] = PATH_THEMES . "/{$this->Theme}/{$ApplicationFolder}/{$SubPath}.*";
                 // $ViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, $ApplicationFolder, 'views', $ControllerName, $View . '.*'));
             }
             // 3. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/controller_name/
             foreach ($SubPaths as $SubPath) {
                 $ViewPaths[] = PATH_THEMES . "/{$this->Theme}/{$SubPath}.*";
                 //$ViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, 'views', $ControllerName, $View . '.*'));
             }
         }
         // 4. Application/plugin default. eg. /path/to/application/app_name/views/controller_name/
         foreach ($SubPaths as $SubPath) {
             $ViewPaths[] = "{$BasePath}/{$ApplicationFolder}/{$SubPath}.*";
             //$ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $ApplicationFolder, 'views', $ControllerName, $View . '.*'));
         }
         // Find the first file that matches the path.
         $ViewPath = false;
         foreach ($ViewPaths as $Glob) {
             $Paths = safeGlob($Glob);
             if (is_array($Paths) && count($Paths) > 0) {
                 $ViewPath = $Paths[0];
                 break;
             }
         }
         //$ViewPath = Gdn_FileSystem::Exists($ViewPaths);
         $this->_ViewLocations[$LocationName] = $ViewPath;
     }
     // echo '<div>['.$LocationName.'] RETURNS ['.$ViewPath.']</div>';
     if ($ViewPath === false && $ThrowError) {
         Gdn::dispatcher()->passData('ViewPaths', $ViewPaths);
         throw NotFoundException('View');
         //         trigger_error(ErrorMessage("Could not find a '$View' view for the '$ControllerName' controller in the '$ApplicationFolder' application.", $this->ClassName, 'FetchViewLocation'), E_USER_ERROR);
     }
     return $ViewPath;
 }
Example #28
0
 /**
  * Get the path to a view.
  *
  * @param string $view the name of the view.
  * @param string $controller the name of the controller invoking the view or blank.
  * @param string $folder the application folder or plugins/<plugin> folder.
  * @param array|null $extensions optional. list of extensions to allow
  * @return string|false The path to the view or false if it wasn't found.
  */
 public static function viewLocation($view, $controller, $folder, $extensions = null)
 {
     $paths = [];
     // If the first character is a forward slash, this is an absolute path
     if (strpos($view, '/') === 0) {
         // This is a path to the view from the root.
         $paths[] = $view;
     } else {
         $view = strtolower($view);
         // Trim "controller" from the end of controller name, if its there
         $controller = strtolower(stringEndsWith($controller, 'Controller', true, true));
         if ($controller) {
             $controller = '/' . $controller;
         }
         // Get list of permitted view extensions
         if (is_null($extensions)) {
             $extensions = AssetModel::viewExtensions();
         }
         // 1. Gather paths from the theme, if enabled
         if (Gdn::controller() instanceof Gdn_Controller) {
             $theme = Gdn::controller()->Theme;
             if ($theme) {
                 foreach ($extensions as $ext) {
                     $paths[] = PATH_THEMES . "/{$theme}/views{$controller}/{$view}.{$ext}";
                 }
             }
         }
         // 2a. Gather paths from the plugin, if the folder is a plugin folder
         if (stringBeginsWith($folder, 'plugins/')) {
             // This is a plugin view.
             foreach ($extensions as $ext) {
                 $paths[] = PATH_ROOT . "/{$folder}/views{$controller}/{$view}.{$ext}";
             }
             // 2b. Gather paths from the application as a fallback
         } else {
             // This is an application view.
             $folder = strtolower($folder);
             foreach ($extensions as $ext) {
                 $paths[] = PATH_APPLICATIONS . "/{$folder}/views{$controller}/{$view}.{$ext}";
             }
             if ($folder != 'dashboard' && stringEndsWith($view, '.master')) {
                 // This is a master view that can always fall back to the dashboard.
                 foreach ($extensions as $ext) {
                     $paths[] = PATH_APPLICATIONS . "/dashboard/views{$controller}/{$view}.{$ext}";
                 }
             }
         }
     }
     // Now let's search the paths for the view.
     foreach ($paths as $path) {
         if (file_exists($path)) {
             return $path;
         }
     }
     trace(['view' => $view, 'controller' => $controller, 'folder' => $folder], 'View');
     trace($paths, __METHOD__);
     return false;
 }
Example #29
0
 /**
  *
  *
  * @param array $Data
  * @param array $Columns The columns/table information for the join. Depending on the argument's index it will be interpreted differently.
  *  - <b>numeric</b>: This column will come be added to the resulting join. The value can be either a string or a two element array where the second element specifies an alias.
  *  - <b>alias</b>: The alias of the child table in the query.
  *  - <b>child</b>: The name of the child column.
  *  - <b>column</b>: The name of the column to put the joined data into. Can't be used with <b>prefix</b>.
  *  - <b>parent</b>: The name of the parent column.
  *  - <b>table</b>: The name of the child table in the join.
  *  - <b>prefix</b>: The name of the prefix to give the columns. Can't be used with <b>column</b>.
  * @param array $Options An array of extra options.
  *  - <b>sql</b>: A Gdn_SQLDriver with the child query.
  *  - <b>type</b>: The join type, either JOIN_INNER, JOIN_LEFT. This defaults to JOIN_LEFT.
  */
 public static function join(&$Data, $Columns, $Options = array())
 {
     $Options = array_change_key_case($Options);
     $Sql = Gdn::sql();
     //GetValue('sql', $Options, Gdn::SQL());
     $ResultColumns = array();
     // Grab the columns.
     foreach ($Columns as $Index => $Name) {
         if (is_numeric($Index)) {
             // This is a column being selected.
             if (is_array($Name)) {
                 $Column = $Name[0];
                 $ColumnAlias = $Name[1];
             } else {
                 $Column = $Name;
                 $ColumnAlias = '';
             }
             if (($Pos = strpos($Column, '.')) !== false) {
                 $Sql->select($Column, '', $ColumnAlias);
                 $Column = substr($Column, $Pos + 1);
             } else {
                 $Sql->select(isset($TableAlias) ? $TableAlias . '.' . $Column : $Column, '', $ColumnAlias);
             }
             if ($ColumnAlias) {
                 $ResultColumns[] = $ColumnAlias;
             } else {
                 $ResultColumns[] = $Column;
             }
         } else {
             switch (strtolower($Index)) {
                 case 'alias':
                     $TableAlias = $Name;
                     break;
                 case 'child':
                     $ChildColumn = $Name;
                     break;
                 case 'column':
                     $JoinColumn = $Name;
                     break;
                 case 'parent':
                     $ParentColumn = $Name;
                     break;
                 case 'prefix':
                     $ColumnPrefix = $Name;
                     break;
                 case 'table':
                     $Table = $Name;
                     break;
                 case 'type':
                     // The type shouldn't be here, but handle it.
                     $Options['Type'] = $Name;
                     break;
                 default:
                     throw new Exception("Gdn_DataSet::Join(): Unknown column option '{$Index}'.");
             }
         }
     }
     if (!isset($TableAlias)) {
         if (isset($Table)) {
             $TableAlias = 'c';
         } else {
             $TableAlias = 'c';
         }
     }
     if (!isset($ParentColumn)) {
         if (isset($ChildColumn)) {
             $ParentColumn = $ChildColumn;
         } elseif (isset($Table)) {
             $ParentColumn = $Table . 'ID';
         } else {
             throw Exception("Gdn_DataSet::Join(): Missing 'parent' argument'.");
         }
     }
     // Figure out some options if they weren't specified.
     if (!isset($ChildColumn)) {
         if (isset($ParentColumn)) {
             $ChildColumn = $ParentColumn;
         } elseif (isset($Table)) {
             $ChildColumn = $Table . 'ID';
         } else {
             throw Exception("Gdn_DataSet::Join(): Missing 'child' argument'.");
         }
     }
     if (!isset($ColumnPrefix) && !isset($JoinColumn)) {
         $ColumnPrefix = stringEndsWith($ParentColumn, 'ID', true, true);
     }
     $JoinType = strtolower(val('Type', $Options, self::JOIN_LEFT));
     // Start augmenting the sql for the join.
     if (isset($Table)) {
         $Sql->from("{$Table} {$TableAlias}");
     }
     $Sql->select("{$TableAlias}.{$ChildColumn}");
     // Get the IDs to generate an in clause with.
     $IDs = array();
     foreach ($Data as $Row) {
         $Value = val($ParentColumn, $Row);
         if ($Value) {
             $IDs[$Value] = true;
         }
     }
     $IDs = array_keys($IDs);
     $Sql->whereIn($ChildColumn, $IDs);
     $ChildData = $Sql->get()->resultArray();
     $ChildData = self::index($ChildData, $ChildColumn, array('unique' => GetValue('unique', $Options, isset($ColumnPrefix))));
     $NotFound = array();
     // Join the data in.
     foreach ($Data as $Index => &$Row) {
         $ParentID = val($ParentColumn, $Row);
         if (isset($ChildData[$ParentID])) {
             $ChildRow = $ChildData[$ParentID];
             if (isset($ColumnPrefix)) {
                 // Add the data to the columns.
                 foreach ($ChildRow as $Name => $Value) {
                     setValue($ColumnPrefix . $Name, $Row, $Value);
                 }
             } else {
                 // Add the result data.
                 setValue($JoinColumn, $Row, $ChildRow);
             }
         } else {
             if ($JoinType == self::JOIN_LEFT) {
                 if (isset($ColumnPrefix)) {
                     foreach ($ResultColumns as $Name) {
                         setValue($ColumnPrefix . $Name, $Row, null);
                     }
                 } else {
                     setValue($JoinColumn, $Row, array());
                 }
             } else {
                 $NotFound[] = $Index;
             }
         }
     }
     // Remove inner join rows.
     if ($JoinType == self::JOIN_INNER) {
         foreach ($NotFound as $Index) {
             unset($Data[$Index]);
         }
     }
 }
Example #30
0
 /**
  * Serves a file to the browser.
  *
  * @param string $File Full path to the file being served.
  * @param string $Name Name to give the file being served. Including extension overrides $File extension. Uses $File filename if empty.
  * @param string $MimeType The mime type of the file.
  * @param string $ServeMode Whether to download the file as an attachment, or inline
  */
 public static function serveFile($File, $Name = '', $MimeType = '', $ServeMode = 'attachment')
 {
     $FileIsLocal = substr($File, 0, 4) == 'http' ? false : true;
     $FileAvailable = $FileIsLocal ? is_readable($File) : true;
     if ($FileAvailable) {
         // Close the database connection
         Gdn::database()->closeConnection();
         // Determine if Path extension should be appended to Name
         $NameExtension = strtolower(pathinfo($Name, PATHINFO_EXTENSION));
         $FileExtension = strtolower(pathinfo($File, PATHINFO_EXTENSION));
         if ($NameExtension == '') {
             if ($Name == '') {
                 $Name = pathinfo($File, PATHINFO_FILENAME) . '.' . $FileExtension;
             } elseif (!stringEndsWith($Name, '.' . $FileExtension)) {
                 $Name .= '.' . $FileExtension;
             }
         } else {
             $Extension = $NameExtension;
         }
         $Name = rawurldecode($Name);
         // Figure out the MIME type
         $MimeTypes = array("pdf" => "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "php" => "text/plain", "ico" => "image/vnd.microsoft.icon");
         if ($MimeType == '') {
             if (array_key_exists($FileExtension, $MimeTypes)) {
                 $MimeType = $MimeTypes[$FileExtension];
             } else {
                 $MimeType = 'application/force-download';
             }
         }
         @ob_end_clean();
         // required for IE, otherwise Content-Disposition may be ignored
         if (ini_get('zlib.output_compression')) {
             ini_set('zlib.output_compression', 'Off');
         }
         if ($ServeMode == 'inline') {
             safeHeader('Content-Disposition: inline; filename="' . $Name . '"');
         } else {
             safeHeader('Content-Disposition: attachment; filename="' . $Name . '"');
         }
         safeHeader('Content-Type: ' . $MimeType);
         safeHeader("Content-Transfer-Encoding: binary");
         safeHeader('Accept-Ranges: bytes');
         safeHeader("Cache-control: private");
         safeHeader('Pragma: private');
         safeHeader("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
         readfile($File);
         exit;
     } else {
         die('not readable');
     }
 }