Exemplo n.º 1
0
 public function onBeforeBrowse()
 {
     // Buttons
     \JToolBarHelper::addNew();
     \JToolBarHelper::editList();
     \JToolBarHelper::divider();
     \JToolBarHelper::publishList();
     \JToolBarHelper::unpublishList();
     \JToolBarHelper::divider();
     $msg = Text::_($this->componentName . '_CONFIRM_DELETE');
     \JToolBarHelper::deleteList(strtoupper($msg));
     return parent::onBeforeBrowse();
     // TODO: Change the autogenerated stub
 }
Exemplo n.º 2
0
 /**
  * Send the mail
  *
  * @return  mixed  True if successful
  *
  * @throws  \RuntimeException
  */
 public function Send()
 {
     $config = $this->container->appConfig;
     if ($config->get('mail.online', true)) {
         if ($this->Mailer == 'mail' && !function_exists('mail')) {
             throw new \RuntimeException(sprintf('%s::Send mail not enabled.', get_class($this)));
         }
         @($result = parent::Send());
         if ($result == false) {
             throw new \RuntimeException(sprintf('%s::Send failed: "%s".', get_class($this), $this->ErrorInfo));
         }
         return $result;
     } else {
         $this->container->application->enqueueMessage(Text::_('AWF_MAIL_FUNCTION_OFFLINE'));
         return false;
     }
 }
Exemplo n.º 3
0
 /**
  * Overrides the default method to execute and display a template script.
  * Instead of loadTemplate is uses loadAnyTemplate.
  *
  * @param   string  $tpl  The name of the template file to parse
  *
  * @return  boolean  True on success
  *
  * @throws  \Exception  When the layout file is not found
  */
 public function display($tpl = null)
 {
     $method = 'onBefore' . ucfirst($this->doTask);
     if (method_exists($this, $method)) {
         $result = $this->{$method}($tpl);
         if (!$result) {
             throw new \Exception(Text::_('AWF_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
         }
     }
     $method = 'onAfter' . ucfirst($this->doTask);
     if (method_exists($this, $method)) {
         $result = $this->{$method}($tpl);
         if (!$result) {
             throw new \Exception(Text::_('AWF_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
         }
     }
     return true;
 }
Exemplo n.º 4
0
 /**
  * Download a part (or the whole) of a remote URL and return the downloaded
  * data. You are supposed to check the size of the returned data. If it's
  * smaller than what you expected you've reached end of file. If it's empty
  * you have tried reading past EOF. If it's larger than what you expected
  * the server doesn't support chunk downloads.
  *
  * If this class' supportsChunkDownload returns false you should assume
  * that the $from and $to parameters will be ignored.
  *
  * @param   string   $url   The remote file's URL
  * @param   integer  $from  Byte range to start downloading from. Use null for start of file.
  * @param   integer  $to    Byte range to stop downloading. Use null to download the entire file ($from is ignored)
  *
  * @return  string  The raw file data retrieved from the remote URL.
  *
  * @throws  \Exception  A generic exception is thrown on error
  */
 public function downloadAndReturn($url, $from = null, $to = null)
 {
     $ch = curl_init();
     if (empty($from)) {
         $from = 0;
     }
     if (empty($to)) {
         $to = 0;
     }
     if ($to < $from) {
         $temp = $to;
         $to = $from;
         $from = $temp;
         unset($temp);
     }
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     if (!(empty($from) && empty($to))) {
         curl_setopt($ch, CURLOPT_RANGE, "{$from}-{$to}");
     }
     $result = curl_exec($ch);
     $errno = curl_errno($ch);
     $errmsg = curl_error($ch);
     $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if ($result === false) {
         $error = Text::sprintf('AWF_DOWNLOAD_ERR_LIB_CURL_ERROR', $errno, $errmsg);
     } elseif ($http_status > 299) {
         $result = false;
         $errno = $http_status;
         $error = Text::sprintf('AWF_DOWNLOAD_ERR_LIB_HTTPERROR', $http_status);
     }
     curl_close($ch);
     if ($result === false) {
         throw new \Exception($error, $errno);
     } else {
         return $result;
     }
 }
Exemplo n.º 5
0
 /**
  * Method to sort a column in a grid
  *
  * @param   string  $title          The link title
  * @param   string  $order          The order field for the column
  * @param   string  $direction      The current direction
  * @param   string  $selected       The selected ordering
  * @param   string  $task           An optional task override
  * @param   string  $new_direction  An optional direction for the new column
  * @param   string  $tip            An optional text shown as tooltip title instead of $title
  * @param   string  $orderingJs     (optional) The Javascript function which handles table reordering, e.g. "Foobar.System.tableOrdering"
  *
  * @return  string
  */
 public static function sort($title, $order, $direction = 'asc', $selected = '', $task = null, $new_direction = 'asc', $tip = '', $orderingJs = '')
 {
     $direction = strtolower($direction);
     $icon = array('caret-up', 'caret-down');
     $index = (int) ($direction == 'desc');
     if ($order != $selected) {
         $direction = $new_direction;
     } else {
         $direction = $direction == 'desc' ? 'asc' : 'desc';
     }
     if (empty($orderingJs)) {
         $orderingJs = self::$javascriptPrefix . 'tableOrdering';
     }
     $html = '<a href="#" onclick="' . $orderingJs . '(\'' . $order . '\',\'' . $direction . '\',\'' . $task . '\');return false;"' . ' class="hasTooltip" title="' . Text::_($tip ? $tip : $title) . '">';
     $html .= Text::_($title);
     if ($order == $selected) {
         $html .= ' <span class="fa fa-' . $icon[$index] . '"></span>';
     }
     $html .= '</a>';
     return $html;
 }
Exemplo n.º 6
0
 /**
  * Method to get the model name
  *
  * The model name. By default parsed using the classname or it can be set
  * by passing a $config['name'] in the class constructor
  *
  * @return  string  The name of the model
  *
  * @throws  \RuntimeException  If it's impossible to get the name
  */
 public function getName()
 {
     if (empty($this->name)) {
         $r = null;
         if (!preg_match('/(.*)\\\\Model\\\\(.*)/i', get_class($this), $r)) {
             throw new \RuntimeException(\Awf\Text\Text::_('AWF_APPLICATION_ERROR_MODEL_GET_NAME'), 500);
         }
         $this->name = strtolower($r[2]);
     }
     return $this->name;
 }
Exemplo n.º 7
0
 /**
  * Method to get the controller name
  *
  * The controller name is set by default parsed using the classname, or it can be set
  * by passing a $config['name'] in the class constructor
  *
  * @return  string  The name of the controller
  *
  * @throws  \Exception  If it's impossible to determine the name and it's not set
  */
 public function getName()
 {
     if (empty($this->name)) {
         $r = null;
         if (!preg_match('/(.*)\\\\Controller\\\\(.*)/i', get_class($this), $r)) {
             throw new \Exception(Text::_('AWF_APPLICATION_ERROR_CONTROLLER_GET_NAME'), 500);
         }
         $this->name = strtolower($r[2]);
     }
     return $this->name;
 }
Exemplo n.º 8
0
 /**
  * The main code of the Dispatcher. It spawns the necessary controller and
  * runs it.
  *
  * @return  void
  *
  * @throws  \Exception
  */
 public function dispatch()
 {
     try {
         $result = $this->onBeforeDispatch();
         $error = '';
     } catch (\Exception $e) {
         $result = false;
         $error = $e->getMessage();
     }
     if (!$result) {
         // For json, don't use normal 403 page, but a json encoded message
         if ($this->input->get('format', '') == 'json') {
             echo json_encode(array('code' => '403', 'error' => $error));
             $this->container->application->close();
         }
         throw new \Exception(Text::_('AWF_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
     }
     // Get and execute the controller
     $view = $this->input->getCmd('view', $this->defaultView);
     $task = $this->input->getCmd('task', 'default');
     if (empty($task)) {
         $task = 'default';
         $this->input->set('task', $task);
     }
     $controller = Mvc\Controller::getInstance($this->container->application_name, $view, $this->container);
     $status = $controller->execute($task);
     if ($status === false) {
         throw new \Exception(Text::_('AWF_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
     }
     if (!$this->onAfterDispatch()) {
         throw new \Exception(Text::_('AWF_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403);
     }
     $controller->redirect();
 }
Exemplo n.º 9
0
 /**
  * Check the data for validity. By default it only checks for fields declared as NOT NULL
  *
  * @return  static  Self, for chaining
  *
  * @throws \RuntimeException  When the data bound to this record is invalid
  */
 public function check()
 {
     if (!$this->autoChecks) {
         return $this;
     }
     foreach ($this->knownFields as $fieldName => $field) {
         // Never check the key if it's empty; an empty key is normal for new records
         if ($fieldName == $this->idFieldName) {
             continue;
         }
         $value = $this->{$fieldName};
         if ($field->Null == 'NO' && empty($value) && !is_numeric($value) && !in_array($fieldName, $this->fieldsSkipChecks)) {
             $text = $this->container->application->getName() . '_' . Inflector::singularize($this->getName()) . '_ERR_' . $fieldName . '_EMPTY';
             throw new \RuntimeException(Text::_($text), 500);
         }
     }
     return $this;
 }
Exemplo n.º 10
0
 /**
  * Generates an HTML radio list.
  *
  * @param   array   $data        An array of objects
  * @param   string  $name        The value of the HTML name attribute
  * @param   string  $attribs     Additional HTML attributes for the <select> tag, or the following
  *                               - inline: boolean Create the radio list as inline elements
  *                               - radioType: radio|checkbox Use radio buttons (radio) or checkboxes (checkbox)
  * @param   mixed   $optKey      The key that is selected
  * @param   string  $optText     The name of the object variable for the option value
  * @param   string  $selected    The name of the object variable for the option text
  * @param   boolean $idtag       Value of the field id or null by default
  * @param   boolean $translate   True if options will be translated
  *
  * @return  string  HTML for the select list
  */
 public static function radioList($data, $name, $attribs = null, $optKey = 'value', $optText = 'text', $selected = null, $idtag = false, $translate = false)
 {
     reset($data);
     $inline = false;
     $button = false;
     $radioType = 'radio';
     if (isset($attribs['inline'])) {
         $inline = $attribs['inline'];
         unset($attribs['inline']);
     }
     if (isset($attribs['radioType'])) {
         $radioType = $attribs['radioType'];
         if (!in_array($radioType, array('radio', 'checkbox'))) {
             $radioType = 'radio';
         }
         unset($attribs['radioType']);
     }
     if (isset($attribs['button'])) {
         $button = $attribs['button'];
         unset($attribs['button']);
     }
     if (is_array($attribs)) {
         $attribs = ArrayHelper::toString($attribs);
     }
     $id_text = $idtag ? $idtag : $name;
     $html = '';
     if ($button) {
         $html .= '<div class="btn-group" data-toggle="buttons">';
     }
     foreach ($data as $obj) {
         $k = $obj->{$optKey};
         $t = $translate ? Text::_($obj->{$optText}) : $obj->{$optText};
         $id = isset($obj->id) ? $obj->id : null;
         $extra = '';
         $id = $id ? $obj->id : $id_text . $k;
         if (is_array($selected)) {
             foreach ($selected as $val) {
                 $k2 = is_object($val) ? $val->{$optKey} : $val;
                 if ($k == $k2) {
                     if ($radioType == 'radio') {
                         $extra .= ' selected="selected" ';
                     } else {
                         $extra .= ' checked="checked" ';
                     }
                     break;
                 }
             }
         } else {
             if ($radioType == 'radio') {
                 $extra .= (string) $k == (string) $selected ? ' checked="checked" ' : '';
             } else {
                 $extra .= (string) $k == (string) $selected ? ' selected="selected" ' : '';
             }
         }
         if (!$inline && !$button) {
             $html .= "\n<div class=\"{$radioType}\">\n";
         }
         $class = '';
         if ($inline) {
             $class = ' class="' . $radioType . '-inline"';
         } elseif ($button) {
             $class = ' class="btn btn-default"';
         }
         $html .= "\n\t" . '<label' . $class . '>';
         $html .= "\n\t\n\t" . '<input type="' . $radioType . '" name="' . $name . '" id="' . $id . '" value="' . $k . '" ' . $extra . $attribs . ' >' . $t;
         $html .= "\n\t" . '</label>';
         if (!$inline && !$button) {
             $html .= "\n</div>\n";
         }
     }
     if ($button) {
         $html .= '</div>';
     }
     return $html;
 }
Exemplo n.º 11
0
 /**
  * Download a part (or the whole) of a remote URL and return the downloaded
  * data. You are supposed to check the size of the returned data. If it's
  * smaller than what you expected you've reached end of file. If it's empty
  * you have tried reading past EOF. If it's larger than what you expected
  * the server doesn't support chunk downloads.
  *
  * If this class' supportsChunkDownload returns false you should assume
  * that the $from and $to parameters will be ignored.
  *
  * @param   string   $url   The remote file's URL
  * @param   integer  $from  Byte range to start downloading from. Use null for start of file.
  * @param   integer  $to    Byte range to stop downloading. Use null to download the entire file ($from is ignored)
  *
  * @return  string  The raw file data retrieved from the remote URL.
  *
  * @throws  \Exception  A generic exception is thrown on error
  */
 public function downloadAndReturn($url, $from = null, $to = null)
 {
     if (empty($from)) {
         $from = 0;
     }
     if (empty($to)) {
         $to = 0;
     }
     if ($to < $from) {
         $temp = $to;
         $to = $from;
         $from = $temp;
         unset($temp);
     }
     if (!(empty($from) && empty($to))) {
         $options = array('http' => array('method' => 'GET', 'header' => "Range: bytes={$from}-{$to}\r\n"));
         $context = stream_context_create($options);
         $result = @file_get_contents($url, false, $context, $from - $to + 1);
     } else {
         $options = array('http' => array('method' => 'GET'));
         $context = stream_context_create($options);
         $result = @file_get_contents($url, false, $context);
     }
     if (!isset($http_response_header)) {
         $error = Text::sprintf('AWF_DOWNLOAD_ERR_LIB_FOPEN_ERROR');
         throw new \Exception($error, 404);
     } else {
         $http_code = 200;
         $nLines = count($http_response_header);
         for ($i = $nLines - 1; $i >= 0; $i--) {
             $line = $http_response_header[$i];
             if (strncasecmp("HTTP", $line, 4) == 0) {
                 $response = explode(' ', $line);
                 $http_code = $response[1];
                 break;
             }
         }
         if ($http_code >= 299) {
             $error = Text::sprintf('AWF_DOWNLOAD_ERR_LIB_FOPEN_ERROR');
             throw new \Exception($error, 404);
         }
     }
     if ($result === false) {
         $error = Text::sprintf('AWF_DOWNLOAD_ERR_LIB_FOPEN_ERROR');
         throw new \Exception($error, 1);
     } else {
         return $result;
     }
 }
Exemplo n.º 12
0
 /**
  * Tries to figure out the page title to use in the Joomla! back-end
  *
  * @return string
  */
 protected function getJoomlaPageTitle()
 {
     $appName = strtoupper($this->getContainer()->application_name);
     if (substr($appName, -5) == 'ADMIN') {
         $appName = substr($appName, 0, -5);
     }
     // e.g. FOOBAR_APP_TITLE
     $appTitle = $appName . '_APP_TITLE';
     // e.g. COM_FOOBAR
     $componentTitle = 'COM_' . $appName;
     // e.g. COM_FOOBAR_ITEMS_TITLE
     $viewTitle = $componentTitle . '_' . strtoupper($this->name) . '_TITLE';
     // e.g. COM_FOOBAR_ITEMS_BROWSE
     $taskTitle = substr($viewTitle, 0, -5) . strtoupper($this->doTask);
     // First try the task-specific title
     $title = Text::_($taskTitle);
     if ($title != $taskTitle) {
         return $title;
     }
     // Then try the view-specific title
     $title = Text::_($viewTitle);
     if ($title != $viewTitle) {
         return $title;
     }
     // Then try the component-specific title
     $title = Text::_($componentTitle);
     if ($title != $componentTitle) {
         return $title;
     }
     // Then try the app-specific title
     $title = Text::_($appTitle);
     if ($title != $appTitle) {
         return $title;
     }
     // If all else fails, try using the generic title...
     $title = Text::_($appName);
     return $title;
 }
Exemplo n.º 13
0
 /**
  * Runs a restoration step and returns an array to be used in the response.
  *
  * @return  array
  *
  * @throws \Exception
  */
 public function stepRestoration()
 {
     $parts = $this->getParam('parts', 1);
     $this->openFile();
     $this->lineNumber = $this->start;
     $this->totalSizeRead = 0;
     $this->queries = 0;
     while ($this->timer->getTimeLeft() > 0) {
         $query = '';
         // Get the next query line
         try {
             $query = $this->readNextLine();
         } catch (\Exception $exc) {
             if ($exc->getCode() == 200) {
                 break;
             } elseif ($exc->getCode() == 201) {
                 continue;
             }
         }
         if (empty($query)) {
             continue;
         }
         // Update variables
         $this->totalSizeRead += strlen($query);
         $this->totalQueries++;
         $this->queries++;
         $this->lineNumber++;
         // Process the query line, running drop/rename queries as necessary
         $this->processQueryLine($query);
     }
     // Get the current file position
     $current_foffset = ftell($this->file);
     if ($current_foffset === false) {
         if (is_resource($this->file)) {
             @fclose($this->file);
         }
         throw new \Exception(Text::_('AWF_RESTORE_ERROR_CANTREADPOINTER'));
     } else {
         if (is_null($this->fileOffset)) {
             $this->fileOffset = 0;
         }
         $bytes_in_step = $current_foffset - $this->fileOffset;
         $this->runSize = (is_null($this->runSize) ? 0 : $this->runSize) + $bytes_in_step;
         $this->fileOffset = $current_foffset;
     }
     // Return statistics
     $bytes_togo = $this->totalSize - $this->runSize;
     // Check for global EOF
     if ($this->currentPart >= $parts - 1 && feof($this->file)) {
         $bytes_togo = 0;
     }
     // Save variables in storage
     $this->setToStorage('start', $this->start);
     $this->setToStorage('foffset', $this->fileOffset);
     $this->setToStorage('totalqueries', $this->totalQueries);
     $this->setToStorage('runsize', $this->runSize);
     if ($bytes_togo == 0) {
         // Clear stored variables if we're finished
         $this->removeInformationFromStorage();
     }
     // Calculate estimated time
     $bytesPerSecond = $bytes_in_step / $this->timer->getRunningTime();
     if ($bytesPerSecond <= 0.01) {
         $remainingSeconds = 120;
     } else {
         $remainingSeconds = round($bytes_togo / $bytesPerSecond, 0);
     }
     // Return meaningful data
     return array('percent' => round(100 * ($this->runSize / $this->totalSize), 1), 'restored' => $this->sizeformat($this->runSize), 'total' => $this->sizeformat($this->totalSize), 'queries_restored' => $this->totalQueries, 'current_line' => $this->lineNumber, 'current_part' => $this->currentPart, 'total_parts' => $parts, 'eta' => $this->etaformat($remainingSeconds), 'error' => '', 'done' => $bytes_togo == 0 ? '1' : '0');
 }
Exemplo n.º 14
0
 /**
  * Create and return the pagination data object.
  *
  * @return  object  Pagination data object.
  */
 protected function _buildDataObject()
 {
     $data = new \stdClass();
     $router = $this->application->getContainer()->router;
     // Build the additional URL parameters string.
     $params = '';
     if (!empty($this->additionalUrlParams)) {
         foreach ($this->additionalUrlParams as $key => $value) {
             $params .= '&' . $key . '=' . $value;
         }
     }
     $params = 'index.php?' . substr($params, 1);
     $data->all = new Object(Text::_('AWF_PAGINATION_LBL_VIEW_ALL'));
     if (!$this->viewAll) {
         $data->all->base = '0';
         $data->all->link = $router->route($params . '&limitstart=');
     }
     // Set the start and previous data objects.
     $data->start = new Object('&laquo;');
     $data->previous = new Object('&lsaquo;');
     if ($this->pagesCurrent > 1) {
         $page = ($this->pagesCurrent - 2) * $this->limit;
         $data->start->base = '0';
         $data->start->link = $router->route($params . '&limitstart=0');
         $data->previous->base = $page;
         $data->previous->link = $router->route($params . '&limitstart=' . $page);
     }
     // Set the next and end data objects.
     $data->next = new Object('&rsaquo;');
     $data->end = new Object('&raquo;');
     if ($this->pagesCurrent < $this->pagesTotal) {
         $next = $this->pagesCurrent * $this->limit;
         $end = ($this->pagesTotal - 1) * $this->limit;
         $data->next->base = $next;
         $data->next->link = $router->route($params . '&limitstart=' . $next);
         $data->end->base = $end;
         $data->end->link = $router->route($params . '&limitstart=' . $end);
     }
     $data->pages = array();
     $stop = $this->pagesStop;
     for ($i = $this->pagesStart; $i <= $stop; $i++) {
         $offset = ($i - 1) * $this->limit;
         $data->pages[$i] = new Object($i);
         if ($i != $this->pagesCurrent || $this->viewAll) {
             $data->pages[$i]->base = $offset;
             $data->pages[$i]->link = $router->route($params . '&limitstart=' . $offset);
         } else {
             $data->pages[$i]->active = true;
         }
     }
     return $data;
 }
Exemplo n.º 15
0
 /**
  * Public constructor
  *
  * @param Container $container Configuration parameters
  *
  * @return Application
  */
 public function __construct(Container $container = null)
 {
     // Start keeping time
     $this->startTime = microtime(true);
     // Create or attach the DI container
     if (!is_object($container) || !$container instanceof Container) {
         $container = new Container();
     }
     $this->container = $container;
     // Set the application name
     if (empty($container['application_name'])) {
         $container->application_name = $this->getName();
     }
     $this->name = $container->application_name;
     // Set up the filesystem path
     if (empty($container['filesystemBase'])) {
         $container->filesystemBase = APATH_BASE;
     }
     // Set up the base path
     if (empty($container['basePath'])) {
         $container->basePath = (defined('APATH_BASE') ? APATH_BASE : $container->filesystemBase) . '/' . ucfirst($this->name);
     }
     // Set up the template path
     if (empty($container['templatePath'])) {
         $container->templatePath = defined('APATH_THEMES') ? APATH_THEMES : $container->filesystemBase . '/templates';
     }
     // Set up the temporary path
     if (empty($container['temporaryPath'])) {
         $container->temporaryPath = defined('APATH_TMP') ? APATH_TMP . '/tmp' : $container->filesystemBase . '/tmp';
     }
     // Set up the language path
     if (empty($container['languagePath'])) {
         $container->languagePath = defined('APATH_TRANSLATION') ? APATH_TRANSLATION : $container->filesystemBase . '/languages';
     }
     // Set up the language path
     if (empty($container['sqlPath'])) {
         $container->sqlPath = defined('APATH_ROOT') ? APATH_ROOT . '/installation/sql' : $container->filesystemBase . '/installation/sql';
     }
     // Start the session
     $this->container->session->start();
     // Forcibly create the session segment
     $segment = $this->container->segment;
     // Set up the template
     $this->setTemplate();
     // Load the translation strings
     Text::addIniProcessCallback(array($this, 'processLanguageIniFile'));
     $languagePath = $container->languagePath;
     Text::loadLanguage(null, $this->name, '.ini', true, $languagePath);
     Text::loadLanguage('en-GB', $this->name, '.ini', false, $languagePath);
 }
Exemplo n.º 16
0
 public function initialise()
 {
     // Put a small marker to indicate that we run inside another CMS
     $this->container->segment->set('insideCMS', true);
     // Load the configuration
     $this->container->appConfig->loadConfiguration();
     // Attach the Joomla!-specific observer for Controller ACL checks
     $this->container->eventDispatcher->attach(new ControllerAcl($this->container->eventDispatcher));
     // Attach the Joomla!-specific observer for template override support
     $this->container->eventDispatcher->attach(new ViewAlternatePaths($this->container->eventDispatcher));
     // Set up the template (theme) to use – different for front-end and back-end
     if (empty($this->template) || $this->template == $this->container->application_name) {
         $template = Helper::isBackend() ? 'backend' : 'frontend';
         $this->setTemplate($template);
     }
     // Load the extra language files
     $appName = $this->container->application_name;
     if (Helper::isBackend() && substr($appName, -5) == 'Admin') {
         $appName = substr($appName, 0, -5);
     }
     $appNameLower = strtolower($appName);
     $languageTag = \JFactory::getLanguage()->getTag();
     Text::loadLanguage('en-GB', $appName, '.com_' . $appNameLower . '.ini', false, $this->container->languagePath);
     Text::loadLanguage($languageTag, $appName, '.com_' . $appNameLower . '.ini', true, $this->container->languagePath);
     // Load the framework's language file
     Text::loadLanguage('en-GB', 'lib_awf', '.ini', false, $this->container->languagePath);
     Text::loadLanguage($languageTag, 'lib_awf', '.ini', false, $this->container->languagePath);
     // In the back-end, also load front-end languages
     if (Helper::isBackend()) {
         Text::loadLanguage('en-GB', $appName, '.com_' . $appNameLower . '.ini', true, JPATH_SITE . '/language');
         Text::loadLanguage($languageTag, $appName, '.com_' . $appNameLower . '.ini', true, JPATH_SITE . '/language');
         Text::loadLanguage('en-GB', 'lib_awf', '.ini', true, JPATH_SITE . '/language');
         Text::loadLanguage($languageTag, 'lib_awf', '.ini', false, JPATH_SITE . '/language');
     }
 }
Exemplo n.º 17
0
 /**
  * Delete selected item(s)
  *
  * @return  void
  */
 public function remove()
 {
     // CSRF prevention
     $this->csrfProtection();
     $model = $this->getModel();
     $ids = $this->getIDsFromRequest($model, false);
     try {
         $status = true;
         foreach ($ids as $id) {
             $model->find($id);
             $model->delete();
         }
     } catch (\Exception $e) {
         $status = false;
         $error = $e->getMessage();
     }
     // Redirect
     if ($customURL = $this->input->getBase64('returnurl', '')) {
         $customURL = base64_decode($customURL);
     }
     $router = $this->container->router;
     $url = !empty($customURL) ? $customURL : $router->route('index.php?view=' . Inflector::pluralize($this->view));
     if (!$status) {
         $this->setRedirect($url, $error, 'error');
     } else {
         $textKey = $this->container->application_name . '_LBL_' . Inflector::singularize($this->view) . '_DELETED';
         $this->setRedirect($url, Text::_($textKey));
     }
 }
Exemplo n.º 18
0
 /**
  * Try to log in a user given the username, password and any additional parameters which may be required by the
  * user class
  *
  * @param   string  $username  The username of the user to log in
  * @param   string  $password  The (unhashed) password of the user to log in
  * @param   array   $params    [optional] Any additional parameters you may want to pass to the user object, e.g. 2FA
  *
  * @return  boolean  True on success
  *
  * @throws  \Exception  When the login fails
  */
 public function loginUser($username, $password, $params = array())
 {
     $user = $this->getUserByUsername($username);
     if (is_null($user)) {
         throw new \RuntimeException(Text::_('AWF_USER_ERROR_AUTHERROR'), 403);
     }
     if (!$user->verifyPassword($password, $params)) {
         throw new \RuntimeException(Text::_('AWF_USER_ERROR_AUTHERROR'), 403);
     }
     $this->container->segment->set('user_id', $user->getId());
     $this->currentUser = $user;
 }
Exemplo n.º 19
0
    /**
     * Displays a calendar control field
     *
     * @param   string       $value    The date value
     * @param   string       $name     The name of the text field
     * @param   string       $id       The id of the text field
     * @param   string       $format   The date format
     * @param   array        $attribs  Additional HTML attributes
     * @param   Application  $app      The application to get the configuration from
     *
     * @return  string  HTML markup for a calendar field
     */
    public static function calendar($value, $name, $id, $format = 'yyyy-mm-dd', $attribs = null, Application $app = null)
    {
        static $done;
        if (!is_object($app)) {
            $app = Application::getInstance();
        }
        if ($done === null) {
            $done = array();
        }
        $attribs['class'] = isset($attribs['class']) ? $attribs['class'] : 'form-control';
        $attribs['class'] = trim($attribs['class'] . ' hasTooltip calendar');
        $readonly = isset($attribs['readonly']) && $attribs['readonly'] == 'readonly';
        $disabled = isset($attribs['disabled']) && $attribs['disabled'] == 'disabled';
        if (is_array($attribs)) {
            $attribs = ArrayHelper::toString($attribs);
        }
        if (!$readonly && !$disabled) {
            // Load the calendar behavior
            Behaviour::calendar();
            // Only display the triggers once for each control.
            if (!in_array($id, $done)) {
                // @todo Implement a way for the application to override the language
                $lang = Text::detectLanguage($app->getName());
                $document = $app->getDocument();
                $document->addScriptDeclaration(<<<JS
akeeba.jQuery(document).ready(function(){
\takeeba.jQuery('#{$id}-container').datepicker({
\t\tformat: "{$format}",
\t\ttodayBtn: "linked",
\t\tlanguage: "{$lang}",
\t\tautoclose: true
\t});
})
JS
);
                $done[] = $id;
            }
            return '<div class="input-group date" id="' . $id . '-container"><input type="text" title="' . (0 !== (int) $value ? static::date($value, null, null) : '') . '" name="' . $name . '" id="' . $id . '" value="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '" ' . $attribs . ' />' . '<span class="input-group-btn" id="' . $id . '_img"><span class="btn btn-default"><span class="glyphicon glyphicon-calendar"></span></span></span></div>';
        } else {
            return '<input type="text" title="' . (0 !== (int) $value ? static::date($value, null, null) : '') . '" value="' . (0 !== (int) $value ? static::_('date', $value, 'Y-m-d H:i:s', null) : '') . '" ' . $attribs . ' /><input type="hidden" name="' . $name . '" id="' . $id . '" value="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '" />';
        }
    }
Exemplo n.º 20
0
 /**
  * Loads a template given any path. The path is in the format:
  * viewname/templatename
  *
  * @param   string $path        The template path
  * @param   array  $forceParams A hash array of variables to be extracted in the local scope of the template file
  *
  * @return  string  The output of the template
  *
  * @throws  \Exception  When the layout file is not found
  */
 public function loadAnyTemplate($path = '', $forceParams = array())
 {
     $template = \Awf\Application\Application::getInstance()->getTemplate();
     $layoutTemplate = $this->getLayoutTemplate();
     // Parse the path
     $templateParts = $this->parseTemplatePath($path);
     // Get the default paths
     $templatePath = $this->container->templatePath;
     $paths = array();
     $paths[] = $templatePath . '/' . $template . '/html/' . $this->input->getCmd('option', '') . '/' . $templateParts['view'];
     $paths[] = $this->container->basePath . '/views/' . $templateParts['view'] . '/tmpl';
     $paths[] = $this->container->basePath . '/View/' . $templateParts['view'] . '/tmpl';
     $paths = array_merge($paths, $this->templatePaths);
     // Look for a template override
     if (isset($layoutTemplate) && $layoutTemplate != '_' && $layoutTemplate != $template) {
         $apath = array_shift($paths);
         array_unshift($paths, str_replace($template, $layoutTemplate, $apath));
     }
     $filetofind = $templateParts['template'] . '.php';
     $this->_tempFilePath = \Awf\Utils\Path::find($paths, $filetofind);
     if ($this->_tempFilePath) {
         // Unset from local scope
         unset($template);
         unset($layoutTemplate);
         unset($paths);
         unset($path);
         unset($filetofind);
         // Never allow a 'this' property
         if (isset($this->this)) {
             unset($this->this);
         }
         // Force parameters into scope
         if (!empty($forceParams)) {
             extract($forceParams);
         }
         // Start capturing output into a buffer
         ob_start();
         // Include the requested template filename in the local scope
         // (this will execute the view logic).
         include $this->_tempFilePath;
         // Done with the requested template; get the buffer and
         // clear it.
         $this->output = ob_get_contents();
         ob_end_clean();
         return $this->output;
     } else {
         return new \Exception(\Awf\Text\Text::sprintf('AWF_APPLICATION_ERROR_LAYOUTFILE_NOT_FOUND', $path), 500);
     }
 }
Exemplo n.º 21
0
 /**
  * Performs the staggered download of file.
  *
  * @param   array $params A parameters array, as sent by the user interface
  *
  * @return  array  A return status array
  */
 public function importFromURL($params)
 {
     $this->params = $params;
     // Fetch data
     $filename = $this->getParam('file');
     $frag = $this->getParam('frag', -1);
     $totalSize = $this->getParam('totalSize', -1);
     $doneSize = $this->getParam('doneSize', -1);
     $maxExecTime = $this->getParam('maxExecTime', 5);
     $runTimeBias = $this->getParam('runTimeBias', 75);
     $minExecTime = $this->getParam('minExecTime', 1);
     $localFilename = 'download.zip';
     $tmpDir = Application::getInstance()->getContainer()->temporaryPath;
     $tmpDir = rtrim($tmpDir, '/\\');
     $localFilename = $this->getParam('localFilename', $localFilename);
     // Init retArray
     $retArray = array("status" => true, "error" => '', "frag" => $frag, "totalSize" => $totalSize, "doneSize" => $doneSize, "percent" => 0);
     try {
         $timer = new Timer($minExecTime, $runTimeBias);
         $start = $timer->getRunningTime();
         // Mark the start of this download
         $break = false;
         // Don't break the step
         // Figure out where on Earth to put that file
         $local_file = $tmpDir . '/' . $localFilename;
         //debugMsg("- Importing from $filename");
         while ($timer->getTimeLeft() > 0 && !$break) {
             // Do we have to initialize the file?
             if ($frag == -1) {
                 //debugMsg("-- First frag, killing local file");
                 // Currently downloaded size
                 $doneSize = 0;
                 if (@file_exists($local_file)) {
                     @unlink($local_file);
                 }
                 // Delete and touch the output file
                 $fp = @fopen($local_file, 'wb');
                 if ($fp !== false) {
                     @fclose($fp);
                 }
                 // Init
                 $frag = 0;
                 //debugMsg("-- First frag, getting the file size");
                 $retArray['totalSize'] = $this->adapter->getFileSize($filename);
                 $totalSize = $retArray['totalSize'];
             }
             // Calculate from and length
             $length = 1048576;
             $from = $frag * $length;
             $to = $length + $from - 1;
             // Try to download the first frag
             $required_time = 1.0;
             //debugMsg("-- Importing frag $frag, byte position from/to: $from / $to");
             try {
                 $result = $this->adapter->downloadAndReturn($filename, $from, $to);
                 if ($result === false) {
                     throw new \Exception(Text::sprintf('AWF_DOWNLOAD_ERR_LIB_COULDNOTDOWNLOADFROMURL', $filename), 500);
                 }
             } catch (\Exception $e) {
                 $result = false;
                 $error = $e->getMessage();
             }
             if ($result === false) {
                 // Failed download
                 if ($frag == 0) {
                     // Failure to download first frag = failure to download. Period.
                     $retArray['status'] = false;
                     $retArray['error'] = $error;
                     //debugMsg("-- Download FAILED");
                     return $retArray;
                 } else {
                     // Since this is a staggered download, consider this normal and finish
                     $frag = -1;
                     //debugMsg("-- Import complete");
                     $totalSize = $doneSize;
                     $break = true;
                 }
             }
             // Add the currently downloaded frag to the total size of downloaded files
             if ($result) {
                 $filesize = strlen($result);
                 //debugMsg("-- Successful download of $filesize bytes");
                 $doneSize += $filesize;
                 // Append the file
                 $fp = @fopen($local_file, 'ab');
                 if ($fp === false) {
                     //debugMsg("-- Can't open local file $local_file for writing");
                     // Can't open the file for writing
                     $retArray['status'] = false;
                     $retArray['error'] = Text::sprintf('AWF_DOWNLOAD_ERR_LIB_COULDNOTWRITELOCALFILE', $local_file);
                     return $retArray;
                 }
                 fwrite($fp, $result);
                 fclose($fp);
                 //debugMsg("-- Appended data to local file $local_file");
                 $frag++;
                 //debugMsg("-- Proceeding to next fragment, frag $frag");
                 if ($filesize < $length || $filesize > $length) {
                     // A partial download or a download larger than the frag size means we are done
                     $frag = -1;
                     //debugMsg("-- Import complete (partial download of last frag)");
                     $totalSize = $doneSize;
                     $break = true;
                 }
             }
             // Advance the frag pointer and mark the end
             $end = $timer->getRunningTime();
             // Do we predict that we have enough time?
             $required_time = max(1.1 * ($end - $start), $required_time);
             if ($required_time > 10 - $end + $start) {
                 $break = true;
             }
             $start = $end;
         }
         if ($frag == -1) {
             $percent = 100;
         } elseif ($doneSize <= 0) {
             $percent = 0;
         } else {
             if ($totalSize > 0) {
                 $percent = 100 * ($doneSize / $totalSize);
             } else {
                 $percent = 0;
             }
         }
         // Update $retArray
         $retArray = array("status" => true, "error" => '', "frag" => $frag, "totalSize" => $totalSize, "doneSize" => $doneSize, "percent" => $percent);
     } catch (\Exception $e) {
         //debugMsg("EXCEPTION RAISED:");
         //debugMsg($e->getMessage());
         $retArray['status'] = false;
         $retArray['error'] = $e->getMessage();
     }
     return $retArray;
 }