示例#1
0
 /**
  * @param string $themeName
  * @param string $lessFile
  * @return string
  */
 public function compileFile($themeName, $lessFile)
 {
     $model = Model::instance();
     $theme = $model->getTheme($themeName);
     $options = $theme->getOptionsAsArray();
     $configModel = ConfigModel::instance();
     $config = $configModel->getAllConfigValues($themeName);
     $less = "@import '{$lessFile}';";
     $less .= $this->generateLessVariables($options, $config);
     $css = '';
     try {
         require_once ipFile('Ip/Lib/less.php/Less.php');
         $themeDir = ipFile('Theme/' . $themeName . '/assets/');
         $ipContentDir = ipFile('Ip/Internal/Core/assets/ipContent/');
         // creating new context to pass theme assets directory dynamically to a static callback function
         $context = $this;
         $callback = function ($parseFile) use($context, $themeDir) {
             return $context->overrideImportDirectory($themeDir, $parseFile);
         };
         $parserOptions = array('import_callback' => $callback, 'cache_dir' => ipFile('file/tmp/less/'), 'relativeUrls' => false, 'sourceMap' => true);
         $parser = new \Less_Parser($parserOptions);
         $directories = array($themeDir => '', $ipContentDir => '');
         $parser->SetImportDirs($directories);
         $parser->parse($less);
         $css = $parser->getCss();
         $css = "/* Edit {$lessFile}, not this file. */" . "\n" . $css;
     } catch (\Exception $e) {
         ipLog()->error('Less compilation error: Theme - ' . $e->getMessage());
     }
     return $css;
 }
示例#2
0
 /**
  * Allocates memory (if required).
  *
  * @param int $bytesRequired
  * @param int $extra in bytes
  * @return bool|null true if enough memory, false if could not allocate, null if there is no way to know
  */
 public static function allocateMemory($bytesRequired, $extra = 0x1000000)
 {
     $memoryLimit = \Ip\Internal\System\Helper\SystemInfo::getMemoryLimit();
     if (!function_exists('memory_get_usage') && $memoryLimit !== '-1') {
         //try to allocate as much as we can
         ini_set('memory_limit', '100M');
         ini_set('memory_limit', '150M');
         ini_set('memory_limit', '200M');
         ini_set('memory_limit', '500M');
         return null;
         // We can't calculate how much memory should be allocated
     }
     if ('-1' == $memoryLimit) {
         // unlimited
         return true;
     }
     $memoryRequired = memory_get_usage() + $bytesRequired;
     if ($memoryRequired < $memoryLimit) {
         return true;
     }
     $megabytesNeeded = ceil($memoryRequired + $extra / 0x100000) . 'M';
     if (!ini_set('memory_limit', $megabytesNeeded)) {
         ipLog()->warning('Could not allocate enough memory. Please increase memory limit to {memoryNeeded}', array('memoryNeeded' => $megabytesNeeded));
         return false;
     }
     return true;
 }
示例#3
0
文件: Job.php 项目: Umz/ImpressPages
 public static function ipRouteAction_20($info)
 {
     if (!$info['request']->_isWebsiteRoot()) {
         return null;
     }
     $req = $info['request']->getRequest();
     if (empty($req)) {
         return null;
     }
     $actionString = null;
     if (isset($req['aa'])) {
         $actionString = $req['aa'];
         $controller = 'AdminController';
     } elseif (isset($req['sa'])) {
         $actionString = $req['sa'];
         $controller = 'SiteController';
     } elseif (isset($req['pa'])) {
         $actionString = $req['pa'];
         $controller = 'PublicController';
     } else {
         return null;
     }
     if (!$actionString) {
         return null;
     }
     $parts = explode('.', $actionString);
     if (count($parts) > 2) {
         ipLog()->warning('Request.invalidControllerAction: {action}', array('action' => $actionString));
         return null;
     }
     if (empty($parts[1])) {
         $parts[1] = 'index';
     }
     return array('plugin' => $parts[0], 'controller' => $controller, 'action' => $parts[1]);
 }
示例#4
0
 /**
  * @return array|string
  */
 public static function getIpNotifications()
 {
     if (!function_exists('curl_init')) {
         return array();
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, \Ip\Internal\System\Model::instance()->getImpressPagesAPIUrl());
     curl_setopt($ch, CURLOPT_POST, 1);
     $postFields = 'module_group=service&module_name=communication&action=getInfo&version=1&afterLogin='******'&systemVersion=' . \Ip\ServiceLocator::storage()->get('Ip', 'version');
     $plugins = \Ip\Internal\Plugins\Model::getActivePlugins();
     foreach ($plugins as $plugin) {
         $postFields .= '&plugins[' . $plugin['name'] . ']=' . $plugin['version'];
     }
     curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
     curl_setopt($ch, CURLOPT_REFERER, ipConfig()->baseUrl());
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_TIMEOUT, 30);
     $answer = curl_exec($ch);
     $notices = json_decode($answer);
     if (!is_array($notices)) {
         // json decode error or wrong answer
         ipLog()->error('System.updateCheckInvalidResponse', array('curl_error' => curl_error($ch), 'response' => $answer));
         return array();
     }
     return $notices;
 }
示例#5
0
 /**
  * Drops the datatable repository db table
  */
 private function dropDataTableRepository()
 {
     $ipTable = ipTable(TableRepository::DATA_TABLE_REPOSITORY);
     $sql = "\n            DROP TABLE {$ipTable}\n        ";
     try {
         ipDb()->execute($sql);
     } catch (\Ip\Exception\Db $e) {
         ipLog()->error("Could not drop repository table. Statement: {$sql}, Message: " . $e->getMessage());
     }
 }
示例#6
0
 public static function ipErrorHandler($errno, $errstr, $errfile, $errline)
 {
     set_error_handler(__CLASS__ . '::ipSilentErrorHandler');
     $type = '';
     switch ($errno) {
         case E_USER_WARNING:
             $type .= 'Warning';
             break;
         case E_USER_NOTICE:
             $type .= 'Notice';
             break;
         case E_WARNING:
             $type .= 'Warning';
             break;
         case E_NOTICE:
             $type .= 'Notice';
             break;
         case E_CORE_WARNING:
             $type .= 'Warning';
             break;
         case E_COMPILE_WARNING:
             $type .= 'Warning';
             break;
         case E_USER_ERROR:
             $type .= 'Error';
             break;
         case E_ERROR:
             $type .= 'Error';
             break;
         case E_PARSE:
             $type .= 'Parse';
             break;
         case E_CORE_ERROR:
             $type .= 'Error';
             break;
         case E_COMPILE_ERROR:
             $type .= 'Error';
             break;
         default:
             $type .= 'Unknown exception';
             break;
     }
     if (class_exists('Ip\\Internal\\Log\\Logger')) {
         ipLog()->error($type . ': ' . $errstr . ' in {file}:{line}', array('file' => $errfile, 'line' => $errline));
     }
     if (ipConfig()->showErrors()) {
         echo "{$errstr} in {$errfile}:{$errline}";
     }
     restore_error_handler();
 }
示例#7
0
 /**
  * Upload file to temporary folder
  */
 public function upload()
 {
     ipRequest()->mustBePost();
     $post = ipRequest()->getPost();
     if (isset($post['secureFolder']) && $post['secureFolder']) {
         //upload to secure publicly not accessible folder.
         if (!ipGetOption('Config.allowAnonymousUploads', 1)) {
             throw new \Exception('Anonymous uploads are not enabled. You can enable them by turning on "anonymous uploads" configuration value in admin.');
         } else {
             //do nothing. Anonymous uploads are allowed to secure folder
         }
         $secureFolder = true;
     } else {
         $secureFolder = false;
         $this->backendOnly();
         if (!ipAdminPermission('Repository upload')) {
             throw new \Ip\Exception('Permission denied');
         }
     }
     $uploadModel = UploadModel::instance();
     try {
         $uploadModel->handlePlupload($secureFolder);
     } catch (\Ip\Exception\Repository\Upload\ForbiddenFileExtension $e) {
         // Return JSON-RPC response
         $message = __('Forbidden file type.', 'Ip-admin');
         ipLog()->info('Repository.invalidUploadedFileExtension: ' . $e->getMessage(), array('plugin' => 'Repository'));
         // TODO JSONRPC
         $answer = array('jsonrpc' => '2.0', 'error' => array('code' => $e->getCode(), 'message' => $message, 'id' => 'id'));
         return new \Ip\Response\Json($answer);
     } catch (\Ip\Exception\Repository\Upload $e) {
         ipLog()->error('Repository.fileUploadError', array('plugin' => 'Repository', 'exception' => $e));
         $message = __('Can\'t store uploaded file. Please check server configuration.', 'Ip-admin');
         // TODO JSONRPC
         $answer = array('jsonrpc' => '2.0', 'error' => array('code' => $e->getCode(), 'message' => $message, 'id' => 'id'));
         return new \Ip\Response\Json($answer);
     }
     $fileName = $uploadModel->getUploadedFileName();
     $file = $uploadModel->getUploadedFile();
     $targetDir = $uploadModel->getTargetDir();
     // Return JSON-RPC response
     $answerArray = array("jsonrpc" => "2.0", "result" => null, "id" => "id", "fileName" => $fileName);
     if (!$secureFolder) {
         $answerArray['dir'] = $targetDir;
         $answerArray['file'] = $file;
     }
     return new \Ip\Response\Json($answerArray);
 }
示例#8
0
 /**
  * @param string $file relative path from file/repository
  * @param array $options - image cropping options
  * @param string $desiredName - desired file name. If reflection is missing, service will try to create new one with name as possible similar to desired
  * @param bool $onDemand transformation will be create on the fly when image accessed for the first time
  * @return string - file name from BASE_DIR
  * @throws \Ip\Exception\Repository\Transform
  */
 public function getReflection($file, $options, $desiredName = null, $onDemand = true)
 {
     $reflectionModel = ReflectionModel::instance();
     try {
         $reflection = $reflectionModel->getReflection($file, $options, $desiredName, $onDemand);
         if (ipConfig()->get('rewritesDisabled') && !is_file(ipFile('file/' . $reflection)) || !ipConfig()->get('realTimeReflections', true)) {
             //create reflections immediately if mod_rewrite is disabled
             $reflectionRecord = $reflectionModel->getReflectionByReflection($reflection);
             $reflectionModel->createReflection($reflectionRecord['original'], $reflectionRecord['reflection'], json_decode($reflectionRecord['options'], true));
         }
     } catch (\Exception $e) {
         ipLog()->error($e->getMessage(), array('errorTrace' => $e->getTraceAsString()));
         $this->lastException = $e;
         return false;
     }
     return 'file/' . $reflection;
 }
示例#9
0
 public function index()
 {
     $this->init();
     if (ipRequest()->getRequest('pass', '') != ipGetOption('Config.cronPassword')) {
         ipLog()->notice('Cron.incorrectPassword: Incorrect cron password from ip `{ip}`.', array('ip' => ipRequest()->getServer('REMOTE_ADDR')));
         $response = new \Ip\Response();
         $response->setContent('Fail. Please see logs for details.');
         return $response;
     }
     ipStorage()->set('Cron', 'lastExecutionStart', time());
     $data = array('firstTimeThisYear' => $this->firstTimeThisYear, 'firstTimeThisMonth' => $this->firstTimeThisMonth, 'firstTimeThisWeek' => $this->firstTimeThisWeek, 'firstTimeThisDay' => $this->firstTimeThisDay, 'firstTimeThisHour' => $this->firstTimeThisHour, 'lastTime' => $this->lastTime, 'test' => ipRequest()->getQuery('test'));
     ipLog()->info('Cron.started', $data);
     ipEvent('ipCronExecute', $data);
     ipStorage()->set('Cron', 'lastExecutionEnd', time());
     ipLog()->info('Cron.finished');
     $response = new \Ip\Response();
     $response->setContent(__('OK', 'Ip-admin'));
     return $response;
 }
示例#10
0
 /**
  * Move files from temporary folder to repository.
  */
 public function storeNewFiles()
 {
     ipRequest()->mustBePost();
     $post = ipRequest()->getPost();
     $secure = !empty($post['secure']);
     $path = isset($post['path']) ? $post['path'] : null;
     $browserModel = BrowserModel::instance();
     $browserModel->pathMustBeInRepository($path, $secure);
     if (!isset($post['files']) || !is_array($post['files'])) {
         return new \Ip\Response\Json(array('status' => 'error', 'errorMessage' => 'Missing POST variable'));
     }
     $files = isset($post['files']) ? $post['files'] : array();
     $newFiles = array();
     $destination = $browserModel->getPath($secure, $path);
     foreach ($files as $file) {
         $sourceDir = 'file/tmp/';
         if ($secure) {
             $sourceDir = 'file/secure/tmp/';
         }
         $source = ipFile($sourceDir . $file['fileName']);
         $source = realpath($source);
         //to avoid any tricks with relative paths, etc.
         if (strpos($source, realpath(ipFile($sourceDir))) !== 0) {
             ipLog()->alert('Core.triedToAccessNonPublicFile', array('file' => $file['fileName']));
             continue;
         }
         $newName = \Ip\Internal\File\Functions::genUnoccupiedName($file['renameTo'], $destination);
         copy($source, $destination . $newName);
         unlink($source);
         //this is a temporary file
         $browserModel = \Ip\Internal\Repository\BrowserModel::instance();
         $newFile = $browserModel->getFile($newName, $secure, $path);
         $newFiles[] = $newFile;
     }
     $answer = array('status' => 'success', 'files' => $newFiles);
     return new \Ip\Response\Json($answer);
 }
示例#11
0
 public static function ipBeforeApplicationClosed()
 {
     /*
      Automatic execution of cron.
      The best solution is to setup cron service to launch file www.yoursite.com/ip_cron.php few times a day.
      By default fake cron is enabled
     */
     if (\Ip\Internal\Admin\Model::isSafeMode() || !ipGetOption('Config.automaticCron', 1)) {
         return;
     }
     $lastExecution = \Ip\ServiceLocator::storage()->get('Cron', 'lastExecutionStart');
     if ($lastExecution && date('Y-m-d H') == date('Y-m-d H', $lastExecution)) {
         // we execute cron once an hour and cron has been executed this hour
         return;
     }
     if (function_exists('curl_init')) {
         $ch = curl_init();
         $url = ipConfig()->baseUrl() . '?pa=Cron&pass='******'Config.cronPassword'));
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_REFERER, ipConfig()->baseUrl());
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_TIMEOUT, ipGetOption('Config.cronTimeout', 10));
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         $fakeCronAnswer = curl_exec($ch);
         if ($fakeCronAnswer != __('OK', 'Ip-admin', false)) {
             ipLog()->error('Cron.failedFakeCron', array('result' => $fakeCronAnswer, 'type' => 'curl', 'error' => curl_error($ch)));
         }
     } else {
         $request = new \Ip\Request();
         $request->setQuery(array('pa' => 'Cron', 'pass' => ipGetOption('Config.cronPassword')));
         $fakeCronAnswer = \Ip\ServiceLocator::application()->handleRequest($request)->getContent();
         if ($fakeCronAnswer != __('OK', 'Ip-admin', false)) {
             ipLog()->error('Cron.failedFakeCron', array('result' => $fakeCronAnswer, 'type' => 'subrequest'));
         }
     }
 }
示例#12
0
 protected static function fetchContent($url)
 {
     if (preg_match('%^\\/\\/%', $url)) {
         $url = 'http:' . $url;
     }
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_SSLVERSION, 3);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     $content = curl_exec($ch);
     $error = curl_error($ch);
     if ($error) {
         ipLog()->debug('ConcatenateJsCss: download asset error', array('url' => $url, 'error' => $error));
         return false;
     }
     $info = curl_getinfo($ch);
     curl_close($ch);
     if (empty($info['http_code']) || $info['http_code'] != '200') {
         return '';
     }
     return $content;
 }
示例#13
0
 /**
  * @param $sourceId
  */
 private static function decrementUsageCounter($sourceId)
 {
     $ipTable = ipTable(self::DATA_TABLE_REPOSITORY);
     $sql = "UPDATE {$ipTable} SET `usageCounter`=`usageCounter`-1 WHERE `sourceId` = '{$sourceId}';";
     try {
         ipDb()->execute($sql);
     } catch (\Ip\Exception\Db $e) {
         ipLog()->error("Could not decrement table usage counter. Statement: {$sql}, Message: " . $e->getMessage());
     }
 }
示例#14
0
 public function setAdminLogin($username)
 {
     $administrator = \Ip\Internal\Administrators\Service::getByUsername($username);
     $ip = ipRequest()->getServer('REMOTE_ADDR');
     Backend::login($administrator['id']);
     ipEvent('ipAdminLoginSuccessful', array('username' => $username, 'id' => $administrator['id']));
     ipLog()->info('Admin.loggedIn: {username} from {ip}', array('username' => $username, 'ip' => $ip));
 }
示例#15
0
 /**
  * We assume page is safe to delete.
  *
  * @param int $pageId
  * @return int Count of deleted pages.
  */
 protected static function _removeDeletedPage($pageId)
 {
     $deletedPageCount = 0;
     $children = ipDb()->selectAll('page', array('id', 'isDeleted'), array('parentId' => $pageId));
     foreach ($children as $child) {
         if ($child['isDeleted']) {
             $deletedPageCount += static::_removeDeletedPage($child['id']);
         } else {
             // This should never happen!
             ipLog()->error('Page.pageHasDeletedParent: page {pageId}, parent set to null', array('pageId' => $child['id']));
             ipDb()->update('page', array('parentId' => null), array('id' => $child['id']));
         }
     }
     ipEvent('ipBeforePageRemoved', array('pageId' => $pageId));
     $count = ipDb()->delete('page', array('id' => $pageId));
     ipPageStorage($pageId)->removeAll();
     ipEvent('ipPageRemoved', array('pageId' => $pageId));
     $deletedPageCount += (int) $count;
     return $deletedPageCount;
 }
示例#16
0
 /**
  * Handle uploads made using PlUpload library
  * @param bool $secureFolder
  * @throws \Ip\Exception\Repository\Upload
  */
 public function handlePlupload($secureFolder)
 {
     if (!$secureFolder && !ipAdminId()) {
         throw new \Ip\Exception\Repository\Upload("Trying to upload image to temporary directory without permission.");
     }
     if ($secureFolder) {
         $targetDir = ipFile('file/secure/tmp/');
     } else {
         $targetDir = ipFile('file/tmp/');
     }
     if ($secureFolder) {
         $sizeLimit = ipGetOption('Repository.publicUploadLimit', 4000);
         if ($this->folderSize($targetDir) > $sizeLimit * 1000000) {
             //4000 Mb by default
             ipLog()->error("Repository.publicUploadLimitReached: IP: `{ip}`. CurrentLimit `{limit}Mb`. Please update Repository.publicUploadLimit option to increase the limits.", array('ip' => $_SERVER['REMOTE_ADDR'], 'limit' => $sizeLimit));
             throw new \Ip\Exception("Upload limit reached");
         }
     }
     // Get parameters
     $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
     $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
     $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
     // Clean the fileName for security reasons
     $fileName = \Ip\Internal\File\Functions::cleanupFileName($fileName);
     // Make sure the fileName is unique but only if chunking is disabled
     if ($chunks < 2 && file_exists($targetDir . $fileName)) {
         $fileName = \Ip\Internal\File\Functions::genUnoccupiedName($fileName, $targetDir);
     }
     //security check
     $fileExtension = strtolower(substr($fileName, strrpos($fileName, '.') + 1));
     $whiteListExtensions = array('jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico', 'asf', 'asx', 'wmv', 'wmx', 'wm', 'avi', 'divx', 'flv', 'mov', 'qt', 'mpeg', 'mpg', 'mpe', 'mp4', 'm4v', 'ogv', 'webm', 'mkv', 'txt', 'asc', 'c', 'cc', 'h', 'csv', 'tsv', 'ics', 'rtx', 'css', 'htm', 'html', 'vtt', 'mp3', 'm4a', 'm4b', 'ra', 'ram', 'wav', 'ogg', 'oga', 'mid', 'midi', 'wma', 'wax', 'mka', 'rtf', 'js', 'pdf', 'class', 'tar', 'zip', 'gz', 'gzip', 'rar', '7z', 'doc', 'pot', 'pps', 'ppt', 'wri', 'xla', 'xls', 'xlt', 'xlw', 'mdb', 'mpp', 'docx', 'docm', 'dotx', 'dotm', 'eps', 'xlsx', 'xlsm', 'xlsb', 'xltx', 'xltm', 'xlam', 'pptx', 'pptm', 'ppsx', 'ppsm', 'potx', 'potm', 'ppam', 'sldx', 'sldm', 'onetoc', 'onetoc2', 'onetmp', 'onepkg', 'odt', 'odp', 'ods', 'odg', 'odc', 'odb', 'odf', 'wp', 'wpd', 'key', 'numbers', 'pages', 'xml', 'json', 'iso', 'aac', 'img', 'psd', 'ai', 'sql', 'swf', 'svg');
     $whiteListExtensions = ipFilter('ipWhiteListExtensions', $whiteListExtensions);
     if (!empty($fileExtension) && !in_array($fileExtension, $whiteListExtensions)) {
         //security risk
         throw new \Ip\Exception\Repository\Upload\ForbiddenFileExtension("Files with extension (." . esc($fileExtension) . ") are not permitted for security reasons.", array('extension' => $fileExtension, 'filename' => $fileName));
     }
     //end security check
     // Look for the content type header
     $contentType = null;
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (!isset($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
             throw new \Ip\Exception\Repository\Upload("Failed to move uploaded file.");
         }
         // Open temp file
         $out = fopen($targetDir . $fileName, $chunk == 0 ? "wb" : "ab");
         if (!$out) {
             throw new \Ip\Exception\Repository\Upload("Failed to open output stream.");
         }
         //mark this file as uploaded by current user
         $this->setFileUploadedByThisUser($targetDir . $fileName);
         // Read binary input stream and append it to temp file
         $in = fopen($_FILES['file']['tmp_name'], "rb");
         if (!$in) {
             throw new \Ip\Exception\Repository\Upload("Failed to open input stream.");
         }
         while ($buff = fread($in, 4096)) {
             fwrite($out, $buff);
         }
         fclose($in);
         fclose($out);
         @unlink($_FILES['file']['tmp_name']);
     } else {
         // Open temp file
         $out = fopen($targetDir . '/' . $fileName, $chunk == 0 ? "wb" : "ab");
         if (!$out) {
             throw new \Ip\Exception\Repository\Upload("Failed to open output stream.");
         }
         // Read binary input stream and append it to temp file
         $in = fopen("php://input", "rb");
         if (!$in) {
             throw new \Ip\Exception\Repository\Upload("Failed to open input stream.");
         }
         while ($buff = fread($in, 4096)) {
             if (function_exists('set_time_limit')) {
                 set_time_limit(30);
             }
             fwrite($out, $buff);
         }
         fclose($in);
         fclose($out);
     }
     $this->uploadedFileName = $fileName;
     $this->uploadedFile = $targetDir . $fileName;
     $this->targetDir = $targetDir;
 }
示例#17
0
/**
 * Get current HTML layout name
 *
 * @return string HTML layout, e.g., "main.php".
 */
function ipGetLayout()
{
    $response = \Ip\ServiceLocator::response();
    if (method_exists($response, 'getLayout')) {
        return $response->getLayout();
    } else {
        ipLog()->error('Response.cantGetLayout: Response method has no method getLayout', array('response' => $response));
    }
    return null;
}
示例#18
0
 public static function removePlugin($pluginName)
 {
     $activePlugins = self::getActivePluginNames();
     if (in_array($pluginName, $activePlugins)) {
         throw new \Ip\Exception\Plugin\Setup('Please deactivate the plugin before removing it.');
     }
     $pluginRecord = self::getPluginRecord($pluginName);
     if ($pluginRecord) {
         $version = $pluginRecord['version'];
     } else {
         $version = null;
     }
     self::executeSqlIfExists(ipFile('Plugin/' . esc($pluginName) . '/Setup/remove.sql'));
     $workerClass = 'Plugin\\' . $pluginName . '\\Setup\\Worker';
     if (method_exists($workerClass, 'remove')) {
         $worker = new $workerClass($version);
         $worker->remove();
     }
     $dbh = ipDb()->getConnection();
     $sql = '
     DELETE FROM
         ' . ipTable('plugin') . '
     WHERE
         `name` = :pluginName
     ';
     $params = array('pluginName' => $pluginName);
     $q = $dbh->prepare($sql);
     $q->execute($params);
     $pluginDir = ipFile('Plugin/' . $pluginName);
     try {
         $result = Helper::removeDir($pluginDir);
         if (!$result) {
             throw new \Ip\Exception\Plugin\Setup('Can\'t remove folder ' . esc($pluginDir));
         }
     } catch (\Ip\PhpException $e) {
         throw new \Ip\Exception\Plugin\Setup('Can\'t remove folder ' . esc($pluginDir));
     }
     ipLog()->info('Ip.pluginRemoved: {plugin} {version} removed.', array('plugin' => $pluginName, 'version' => $version));
     ipEvent('ipPluginRemoved', array('name' => $pluginName, 'version' => $version));
 }
示例#19
0
文件: File.php 项目: Umz/ImpressPages
 /**
  * Original file names
  *
  * @param $values
  * @param $valueKey
  * @return array
  * @throws \Exception
  */
 public static function originalFileNames($values, $valueKey)
 {
     if (isset($values[$valueKey]['file']) && is_array($values[$valueKey]['file'])) {
         $answer = array();
         foreach ($values[$valueKey]['file'] as $key => $file) {
             $uploadModel = \Ip\Internal\Repository\UploadModel::instance();
             if (!$uploadModel->isFileUploadedByCurrentUser($file, true)) {
                 ipLog()->alert('Core.tryToAccessNotUploadedFile', array('file' => $file));
                 continue;
             }
             $originalFileName = $file;
             if (isset($values[$valueKey]['originalFileName'][$key]) && is_string($values[$valueKey]['originalFileName'][$key])) {
                 $originalFileName = $values[$valueKey]['originalFileName'][$key];
             }
             $answer[] = $originalFileName;
         }
         return $answer;
     } else {
         return array();
     }
 }
示例#20
0
 public function update($widgetId, $postData, $currentData)
 {
     if (isset($postData['method'])) {
         switch ($postData['method']) {
             case 'resize':
                 $newData = $currentData;
                 if (!isset($postData['width']) || !$postData['height']) {
                     ipLog()->error("Image widget resize missing required parameter", $postData);
                     throw new \Ip\Exception("Missing required data");
                 }
                 $newData['width'] = $postData['width'];
                 $newData['height'] = $postData['height'];
                 return $newData;
                 break;
             case 'autosize':
                 unset($currentData['width']);
                 unset($currentData['height']);
                 return $currentData;
                 break;
             case 'update':
                 $newData = $currentData;
                 if (isset($postData['fileName']) && is_file(ipFile('file/repository/' . $postData['fileName']))) {
                     //unbind old image
                     if (isset($currentData['imageOriginal']) && $currentData['imageOriginal']) {
                         \Ip\Internal\Repository\Model::unbindFile($currentData['imageOriginal'], 'Content', $widgetId);
                     }
                     //bind new image
                     \Ip\Internal\Repository\Model::bindFile($postData['fileName'], 'Content', $widgetId);
                     $newData['imageOriginal'] = $postData['fileName'];
                 }
                 if (isset($postData['cropX1']) && isset($postData['cropY1']) && isset($postData['cropX2']) && isset($postData['cropY2'])) {
                     //new small image
                     $newData['cropX1'] = $postData['cropX1'];
                     $newData['cropY1'] = $postData['cropY1'];
                     $newData['cropX2'] = $postData['cropX2'];
                     $newData['cropY2'] = $postData['cropY2'];
                 }
                 return $newData;
                 break;
             case 'setLink':
                 if (isset($postData['type'])) {
                     $currentData['type'] = $postData['type'];
                 }
                 if (isset($postData['url'])) {
                     $currentData['url'] = $postData['url'];
                 }
                 if (isset($postData['blank'])) {
                     $currentData['blank'] = (int) $postData['blank'];
                 }
                 if (isset($postData['nofollow'])) {
                     $currentData['nofollow'] = (int) $postData['nofollow'];
                 }
                 return $currentData;
                 break;
             case 'saveSettings':
                 if (isset($postData['title'])) {
                     $currentData['title'] = $postData['title'];
                 }
                 if (isset($postData['description'])) {
                     $currentData['description'] = $postData['description'];
                 }
                 return $currentData;
                 break;
         }
     }
     return $currentData;
 }
示例#21
0
 /**
  *
  *
  * @param int $widgetId
  * @param array $data
  * @return \Ip\Form
  */
 protected function createForm($widgetId, $data)
 {
     $form = new \Ip\Form();
     $form->setEnvironment(\Ip\Form::ENVIRONMENT_PUBLIC);
     if (empty($data['fields']) || !is_array($data['fields'])) {
         $data['fields'] = array();
     }
     foreach ($data['fields'] as $fieldKey => $field) {
         if (!isset($field['type']) || !isset($field['label'])) {
             continue;
         }
         if ($field['type'] == 'Fieldset') {
             $label = empty($field['label']) ? '' : $field['label'];
             $form->addFieldset(new \Ip\Form\Fieldset($label));
             continue;
         }
         if (!isset($field['options'])) {
             $field['options'] = array();
         }
         if (!isset($field['options']) || !is_array($field['options'])) {
             $field['options'] = array();
         }
         if (!isset($field['required'])) {
             $field['required'] = false;
         }
         $fieldType = Model::getFieldType($field['type']);
         if ($fieldType) {
             $fieldData = array('label' => $field['label'], 'name' => 'ipForm_field_' . $fieldKey, 'required' => $field['required'], 'options' => $field['options']);
             try {
                 $newField = $fieldType->createField($fieldData);
                 $form->addField($newField);
             } catch (\Ip\Exception\Content $e) {
                 ipLog()->error('FormWidget.failedAddField: Widget failed to add field.', array('widget' => 'Form', 'exception' => $e, 'fieldData' => $fieldData));
             }
         }
     }
     //special variable to post to widget controller
     $field = new \Ip\Form\Field\Hidden(array('name' => 'sa', 'value' => 'Content.widgetPost'));
     $form->addField($field);
     $field = new \Ip\Form\Field\Hidden(array('name' => 'widgetId', 'value' => $widgetId));
     $form->addField($field);
     //antispam
     $field = new \Ip\Form\Field\Antispam(array('name' => 'checkField'));
     $form->addField($field);
     //submit
     if (!empty($data['buttonText'])) {
         $value = $data['buttonText'];
     } else {
         $value = __('Send', 'Ip', false);
     }
     $field = new \Ip\Form\Field\Submit(array('value' => $value));
     $form->addField($field);
     return $form;
 }
示例#22
0
 private static function findPluginWidgets($moduleName)
 {
     $widgetDir = ipFile('Plugin/' . $moduleName . '/' . Model::WIDGET_DIR . '/');
     if (!is_dir($widgetDir)) {
         return array();
     }
     $widgetFolders = scandir($widgetDir);
     if ($widgetFolders === false) {
         return array();
     }
     $answer = array();
     //foreach all widget folders
     foreach ($widgetFolders as $widgetFolder) {
         //each directory is a widget
         if (!is_dir($widgetDir . $widgetFolder) || $widgetFolder == '.' || $widgetFolder == '..') {
             continue;
         }
         if (isset($answer[(string) $widgetFolder])) {
             ipLog()->warning('Content.duplicateWidget: {widget}', array('plugin' => 'Content', 'widget' => $widgetFolder));
         }
         $answer[] = array('module' => $moduleName, 'dir' => $widgetDir . $widgetFolder . '/', 'widgetKey' => $widgetFolder);
     }
     return $answer;
 }
示例#23
0
 /**
  * PHP can't handle exceptions in __toString method. Try to avoid it every time possible. Use render() method instead.
  * @ignore
  * @return string
  */
 public function __toString()
 {
     try {
         $content = $this->render();
     } catch (\Exception $e) {
         /*
         __toString method can't throw exceptions. In case of exception you will end with unclear error message.
         We can't avoid that here. So just logging clear error message in logs and rethrowing the same exception.
         */
         ipLog()->error('Block.toStringException: Exception in block `{block}` __toString() method.', array('block' => $this->name, 'exception' => $e));
         return $e->getTraceAsString();
     }
     return $content;
 }
示例#24
0
 /**
  * PHP can't handle exceptions in __toString method. Try to avoid it every time possible. Use render() method instead.
  * @ignore
  * @return string
  */
 public function __toString()
 {
     try {
         $content = $this->render();
     } catch (\Exception $e) {
         /*
         __toString method can't throw exceptions. In case of exception you will end with unclear error message.
         We can't avoid that here. So just logging clear error message in logs and rethrowing the same exception.
         */
         ipLog()->error('View.toStringException: Exception in View::__toString() method.', array('exception' => $e, 'view' => $this->file));
         if (ipConfig()->isDevelopmentEnvironment()) {
             return "<pre class=\"error\">\n" . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n</pre>";
         } else {
             return '';
         }
     }
     return $content;
 }
示例#25
0
 /**
  * Checks if there are some emails waiting in queue and sends them if possible.
  */
 function send()
 {
     $alreadySent = Db::sentOrLockedCount(60);
     if ($alreadySent !== false) {
         $available = floor(ipGetOption('Email.hourlyLimit') * 0.8 - $alreadySent);
         //20% for immediate emails
         $lockKey = md5(uniqid(rand(), true));
         if ($available > 0) {
             if ($available > 5 && !defined('CRON')) {
                 //only cron job can send many emails at once.
                 $available = 5;
             }
             $locked = Db::lock($available, $lockKey);
         } else {
             $available = 0;
             $locked = 0;
         }
         if ($locked == $available) {
             //if in queue left some messages
             if (ipGetOption('Email.hourlyLimit') - ($alreadySent + $available) > 0) {
                 $locked = $locked + Db::lockOnlyImmediate(ipGetOption('Email.hourlyLimit') - ($alreadySent + $available), $lockKey);
             }
         }
         if ($locked) {
             $emails = Db::getLocked($lockKey);
             foreach ($emails as $key => $email) {
                 if (function_exists('set_time_limit')) {
                     set_time_limit((sizeof($emails) - $key) * 10 + 100);
                 }
                 $mail = new \PHPMailer();
                 /*          $mail->Sender = $email['from'];
                             $mail->addCustomHeader("Return-Path: " . $email['from']);*/
                 $mail->From = $email['from'];
                 $mail->FromName = $email['fromName'];
                 $mail->AddReplyTo($email['from'], $email['fromName']);
                 $mail->WordWrap = 50;
                 // set word wrap
                 $mail->CharSet = ipConfig()->get('charset');
                 $mail->Subject = $email['subject'];
                 /*	foreach($this->posted_files as $file){
                    if(isset($_FILES[$file]['tmp_name']) && $_FILES[$file]['error'] == 0){
                    $mail->AddAttachment($_FILES[$file]['tmp_name'], $_FILES[$file]['name']);
                    }
                    }*/
                 $files = explode("\n", $email['files']);
                 $fileNames = explode("\n", $email['fileNames']);
                 $fileMimeTypes = explode("\n", $email['fileMimeTypes']);
                 $fileCount = min(count($files), count($fileNames), count($fileMimeTypes));
                 for ($i = 0; $i < $fileCount; $i++) {
                     if ($files[$i] != '') {
                         if ($fileMimeTypes[$i] == '') {
                             $answer = $mail->AddAttachment($files[$i], $fileNames[$i]);
                         } else {
                             $answer = $mail->AddAttachment($files[$i], $fileNames[$i], "base64", $fileMimeTypes[$i]);
                         }
                         if (!$answer) {
                             ipLog()->error('Email.addAttachmentFailed: {subject} to {to}', array('to' => $email['to'], 'subject' => $email['subject'], 'filename' => $fileNames[$i]));
                             return false;
                         }
                     }
                 }
                 if ($email['html']) {
                     $mail->IsHTML(true);
                     // send as HTML
                     $mail->MsgHTML($email['email']);
                     try {
                         $altBody = \Ip\Internal\Text\Html2Text::convert($email['email']);
                     } catch (\Ip\Internal\Text\Html2TextException $e) {
                         $altBody = $email['email'];
                     }
                     $mail->AltBody = $altBody;
                 } else {
                     /*$h2t = new \Ip\Internal\Text\Html2Text($content, false);
                       $mail->Body  =  $h2t->get_text();*/
                     $mail->Body = $email['email'];
                 }
                 $mail->AddAddress($email['to'], $email['toName']);
                 $mail = ipFilter('ipSendEmailPHPMailerObject', $mail, $email);
                 if (!$mail->Send()) {
                     ipLog()->error('Email.sendFailed: {subject} to {to}', array('to' => $email['to'], 'subject' => $email['subject'], 'body' => $email['email']));
                     return false;
                 }
                 if (sizeof($emails) > 5) {
                     sleep(1);
                 }
                 Db::unlockOne($email['id']);
             }
         }
     }
     return null;
 }
示例#26
0
 /**
  * @ignore
  * @param Request $request
  * @param array $options
  * @param bool $subrequest
  * @return Response\Json|Response\PageNotFound|Response\Redirect
  * @throws Exception
  * @ignore
  */
 public function _handleOnlyRequest(\Ip\Request $request, $options = array(), $subrequest = true)
 {
     if (empty($options['skipInitEvents'])) {
         \Ip\ServiceLocator::dispatcher()->_bindApplicationEvents();
     }
     $result = ipJob('ipRouteLanguage', array('request' => $request, 'relativeUri' => $request->getRelativePath()));
     if ($result) {
         $requestLanguage = $result['language'];
         $routeLanguage = $requestLanguage->getCode();
         ipRequest()->_setRoutePath($result['relativeUri']);
     } else {
         $routeLanguage = null;
         $requestLanguage = ipJob('ipRequestLanguage', array('request' => $request));
         ipRequest()->_setRoutePath($request->getRelativePath());
     }
     //find out and set locale
     $locale = $requestLanguage->getCode();
     if (strlen($locale) == '2') {
         $locale = strtolower($locale) . '_' . strtoupper($locale);
     } else {
         $locale = str_replace('-', '_', $locale);
     }
     $locale .= '.utf8';
     if ($locale == "tr_TR.utf8" && (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION < 5)) {
         //Overcoming this bug https://bugs.php.net/bug.php?id=18556
         setlocale(LC_COLLATE, $locale);
         setlocale(LC_MONETARY, $locale);
         setlocale(LC_NUMERIC, $locale);
         setlocale(LC_TIME, $locale);
         setlocale(LC_MESSAGES, $locale);
         setlocale(LC_CTYPE, "en_US.utf8");
     } else {
         setLocale(LC_ALL, $locale);
     }
     setlocale(LC_NUMERIC, "C");
     //user standard C syntax for numbers. Otherwise you will get funny things with when autogenerating CSS, etc.
     ipContent()->_setCurrentLanguage($requestLanguage);
     $_SESSION['ipLastLanguageId'] = $requestLanguage->getId();
     if (empty($options['skipTranslationsInit'])) {
         if (!empty($options['translationsLanguageCode'])) {
             $languageCode = $options['translationsLanguageCode'];
         } else {
             $languageCode = $requestLanguage->getCode();
         }
         $this->initTranslations($languageCode);
     }
     if (empty($options['skipModuleInit'])) {
         $this->modulesInit();
     }
     ipEvent('ipInitFinished');
     $routeAction = ipJob('ipRouteAction', array('request' => $request, 'relativeUri' => ipRequest()->getRoutePath(), 'routeLanguage' => $routeLanguage));
     if (!empty($routeAction)) {
         if (!empty($routeAction['page'])) {
             ipContent()->_setCurrentPage($routeAction['page']);
         }
         if (!empty($routeAction['environment'])) {
             ipRoute()->setEnvironment($routeAction['environment']);
         } else {
             if (!empty($routeAction['controller']) && $routeAction['controller'] == 'AdminController') {
                 ipRoute()->setEnvironment(\Ip\Route::ENVIRONMENT_ADMIN);
             } else {
                 ipRoute()->setEnvironment(\Ip\Route::ENVIRONMENT_PUBLIC);
             }
         }
         if (!empty($routeAction['controller'])) {
             ipRoute()->setController($routeAction['controller']);
         }
         if (!empty($routeAction['plugin'])) {
             ipRoute()->setPlugin($routeAction['plugin']);
         }
         if (!empty($routeAction['name'])) {
             ipRoute()->setName($routeAction['name']);
         }
         if (!empty($routeAction['action'])) {
             ipRoute()->setAction($routeAction['action']);
         }
     }
     //check for CSRF attack
     if (empty($options['skipCsrfCheck']) && $request->isPost() && $request->getPost('securityToken') != $this->getSecurityToken() && (empty($routeAction['controller']) || $routeAction['controller'] != 'PublicController')) {
         ipLog()->error('Core.possibleCsrfAttack', array('post' => ipRequest()->getPost()));
         $data = array('status' => 'error');
         if (ipConfig()->isDevelopmentEnvironment()) {
             $data['errors'] = array('securityToken' => __('Possible CSRF attack. Please pass correct securityToken.', 'Ip-admin'));
         }
         // TODO JSONRPC
         return new \Ip\Response\Json($data);
     }
     if (empty($routeAction)) {
         $routeAction = array('plugin' => 'Core', 'controller' => 'PublicController', 'action' => 'pageNotFound');
     }
     $eventInfo = $routeAction;
     if (!empty($routeAction['plugin'])) {
         $plugin = $routeAction['plugin'];
         $controller = $routeAction['controller'];
         if (in_array($plugin, \Ip\Internal\Plugins\Model::getModules())) {
             $controllerClass = 'Ip\\Internal\\' . $plugin . '\\' . $controller;
         } else {
             if (!in_array($plugin, \Ip\Internal\Plugins\Service::getActivePluginNames())) {
                 throw new \Ip\Exception("Plugin '" . esc($plugin) . "' doesn't exist or isn't activated.");
             }
             $controllerClass = 'Plugin\\' . $plugin . '\\' . $controller;
         }
         if (!class_exists($controllerClass)) {
             throw new \Ip\Exception('Requested controller doesn\'t exist. ' . esc($controllerClass));
         }
         // check if user is logged in
         if ($controller == 'AdminController' && !\Ip\Internal\Admin\Backend::userId()) {
             if (ipConfig()->get('rewritesDisabled')) {
                 return new \Ip\Response\Redirect(ipConfig()->baseUrl() . 'index.php/admin');
             } else {
                 return new \Ip\Response\Redirect(ipConfig()->baseUrl() . 'admin');
             }
         }
         if ($controller == 'AdminController') {
             if (!ipAdminPermission($plugin)) {
                 throw new \Ip\Exception('User has no permission to access ' . esc($plugin) . '');
             }
         }
         $eventInfo['controllerClass'] = $controllerClass;
         $eventInfo['controllerType'] = $controller;
     }
     if (empty($eventInfo['page'])) {
         $eventInfo['page'] = null;
     }
     // change layout if safe mode
     if (\Ip\Internal\Admin\Service::isSafeMode()) {
         ipSetLayout(ipFile('Ip/Internal/Admin/view/safeModeLayout.php'));
     } else {
         if ($eventInfo['page']) {
             ipSetLayout($eventInfo['page']->getLayout());
         }
     }
     ipEvent('ipBeforeController', $eventInfo);
     $controllerAnswer = ipJob('ipExecuteController', $eventInfo);
     return $controllerAnswer;
 }
示例#27
0
 /**
  * Creates the DB table
  */
 private function createDbTableIfNotExists()
 {
     $ipTable = ipTable($this->_name);
     $attributeDefinition = '';
     foreach ($this->_columns as $column) {
         $attributeDefinition .= ' `' . $column['attribute'] . '` varchar(255),';
     }
     $sql = "\n          CREATE TABLE IF NOT EXISTS {$ipTable}\n          (\n            `id` int(11) NOT NULL AUTO_INCREMENT,\n            {$attributeDefinition}\n            PRIMARY KEY (`id`)\n          ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;";
     try {
         ipDb()->execute($sql);
     } catch (\Ip\Exception\Db $e) {
         ipLog()->error("Could not create data table. Statement: {$sql}, Message: " . $e->getMessage());
         throw $e;
     }
 }