Пример #1
0
 /**
  * Shows the data formatted for the list view
  *
  * @param   string    $data      Elements data
  * @param   stdClass  &$thisRow  All the data in the lists current row
  * @param   array     $opts      Rendering options
  *
  * @return  string	formatted value
  */
 public function renderListData($data, stdClass &$thisRow, $opts = array())
 {
     $listModel = $this->getListModel();
     $params = $this->getParams();
     $w = (int) $params->get('fb_gm_table_mapwidth');
     $h = (int) $params->get('fb_gm_table_mapheight');
     $z = (int) $params->get('fb_gm_table_zoomlevel');
     $data = FabrikWorker::JSONtoData($data, true);
     foreach ($data as $i => &$d) {
         if ($params->get('fb_gm_staticmap_tableview')) {
             $d = $this->_staticMap($d, $w, $h, $z, $i, true, ArrayHelper::fromObject($thisRow));
         }
         if ($params->get('icon_folder') == '1' && ArrayHelper::getValue($opts, 'icon', 1)) {
             // $$$ rob was returning here but that stopped us being able to use links and icons together
             $d = $this->replaceWithIcons($d, 'list', $listModel->getTmpl());
         } else {
             if (!$params->get('fb_gm_staticmap_tableview')) {
                 $d = $params->get('fb_gm_staticmap_tableview_type_coords', 'num') == 'dms' ? $this->_dmsformat($d) : $this->_microformat($d);
             }
         }
         if (ArrayHelper::getValue($opts, 'rollover', 1)) {
             $d = $this->rollover($d, $thisRow, 'list');
         }
         if (ArrayHelper::getValue($opts, 'link', 1)) {
             $d = $listModel->_addLink($d, $this, $thisRow, $i);
         }
     }
     return $this->renderListDataFinal($data);
 }
Пример #2
0
 /**
  * Get the foreign keys value.
  *
  * @return  mixed string|int
  */
 protected function fkData()
 {
     if (!isset($this->fkData)) {
         /** @var FabrikFEModelForm $formModel */
         $formModel = $this->getModel();
         $params = $this->getParams();
         $this->fkData = array();
         // Get the foreign key element
         $fkElement = $this->fkElement();
         if ($fkElement) {
             $fkElementKey = $fkElement->getFullName();
             $this->fkData = json_decode(FArrayHelper::getValue($formModel->formData, $fkElementKey));
             if (is_object($this->fkData)) {
                 $this->fkData = ArrayHelper::fromObject($this->fkData);
             }
             $fkEval = $params->get('foreign_key_eval', '');
             if ($fkEval !== '') {
                 $fkData = $this->fkData;
                 $eval = eval($fkEval);
                 if ($eval !== false) {
                     $this->fkData = $eval;
                 }
             }
         }
     }
     return $this->fkData;
 }
Пример #3
0
 /**
  * Method to render the view.
  *
  * @return  string  The rendered view.
  *
  * @since   1.0
  * @throws  \RuntimeException
  */
 public function render()
 {
     // Set the vars to the template.
     $this->renderer->set('group', ArrayHelper::fromObject($this->model->getItem()));
     $this->renderer->set('project', $this->getProject());
     return parent::render();
 }
Пример #4
0
/**
 * Disables the unsupported eAccelerator caching method, replacing it with the "file" caching method.
 *
 * @return  void
 *
 * @since   3.2
 */
function admin_postinstall_eaccelerator_action()
{
    $prev = ArrayHelper::fromObject(new JConfig());
    $data = array_merge($prev, array('cacheHandler' => 'file'));
    $config = new Registry($data);
    jimport('joomla.filesystem.path');
    jimport('joomla.filesystem.file');
    // Set the configuration file path.
    $file = JPATH_CONFIGURATION . '/configuration.php';
    // Get the new FTP credentials.
    $ftp = JClientHelper::getCredentials('ftp', true);
    // Attempt to make the file writeable if using FTP.
    if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0644')) {
        JError::raiseNotice('SOME_ERROR_CODE', JText::_('COM_CONFIG_ERROR_CONFIGURATION_PHP_NOTWRITABLE'));
    }
    // Attempt to write the configuration file as a PHP class named JConfig.
    $configuration = $config->toString('PHP', array('class' => 'JConfig', 'closingtag' => false));
    if (!JFile::write($file, $configuration)) {
        JFactory::getApplication()->enqueueMessage(JText::_('COM_CONFIG_ERROR_WRITE_FAILED'), 'error');
        return;
    }
    // Attempt to make the file unwriteable if using FTP.
    if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0444')) {
        JError::raiseNotice('SOME_ERROR_CODE', JText::_('COM_CONFIG_ERROR_CONFIGURATION_PHP_NOTUNWRITABLE'));
    }
}
Пример #5
0
 /**
  * Short cut for getting the element's filter value, or false if no value
  *
  * @param   int  $elementId  Element id
  *
  * @since   3.0.7
  *
  * @return  mixed
  */
 public static function filterValue($elementId)
 {
     $app = JFactory::getApplication();
     $pluginManager = FabrikWorker::getPluginManager();
     $model = $pluginManager->getElementPlugin($elementId);
     $listModel = $model->getListModel();
     $listId = $listModel->getId();
     $key = 'com_fabrik.list' . $listId . '_com_fabrik_' . $listId . '.filter';
     $filters = ArrayHelper::fromObject($app->getUserState($key));
     $elementIds = (array) FArrayHelper::getValue($filters, 'elementid', array());
     $index = array_search($elementId, $elementIds);
     $value = $index === false ? false : FArrayHelper::getValue($filters['value'], $index, false);
     return $value;
 }
Пример #6
0
 /**
  * Can the row be deleted
  *
  * @param   object  $row  Current row to test
  *
  * @return boolean
  */
 public function onCanDelete($row)
 {
     $params = $this->getParams();
     // If $row is null, we were called from the table's canEdit() in a per-table rather than per-row context,
     // and we don't have an opinion on per-table delete permissions, so just return true.
     if (is_null($row) || is_null($row[0])) {
         return true;
     }
     if (is_array($row[0])) {
         $data = ArrayHelper::toObject($row[0]);
     } else {
         $data = $row[0];
     }
     $field = str_replace('.', '___', $params->get('candeleterow_field'));
     // If they provided some PHP to eval, we ignore the other settings and just run their code
     $canDeleteRowEval = $params->get('candeleterow_eval', '');
     // $$$ rob if no can delete field selected in admin return true
     if (trim($field) == '' && trim($canDeleteRowEval) == '') {
         return true;
     }
     if (!empty($canDeleteRowEval)) {
         $w = new FabrikWorker();
         $data = ArrayHelper::fromObject($data);
         $canDeleteRowEval = $w->parseMessageForPlaceHolder($canDeleteRowEval, $data);
         FabrikWorker::clearEval();
         $canDeleteRowEval = @eval($canDeleteRowEval);
         FabrikWorker::logEval($canDeleteRowEval, 'Caught exception on eval in can delete row : %s');
         return $canDeleteRowEval;
     } else {
         // No PHP given, so just do a simple match on the specified element and value settings.
         if ($params->get('candeleterow_useraw', '0') == '1') {
             $field .= '_raw';
         }
         $value = $params->get('candeleterow_value');
         $operator = $params->get('operator', '=');
         if (!isset($data->{$field})) {
             return false;
         }
         switch ($operator) {
             case '=':
             default:
                 return $data->{$field} == $value;
                 break;
             case "!=":
                 return $data->{$field} != $value;
                 break;
         }
     }
 }
Пример #7
0
 /**
  * Display a json object representing the table data.
  *
  * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
  *
  * @return  void
  */
 public function display($tpl = null)
 {
     $app = JFactory::getApplication();
     $input = $app->input;
     $model = JModelLegacy::getInstance('List', 'FabrikFEModel');
     $model->setId($input->getInt('listid'));
     $this->setModel($model, true);
     $item = $model->getTable();
     $params = $model->getParams();
     $model->render();
     $this->emptyDataMessage = FText::_($params->get('empty_data_msg', 'COM_FABRIK_LIST_NO_DATA_MSG'));
     $rowid = $input->getString('rowid', '', 'string');
     list($this->headings, $groupHeadings, $this->headingClass, $this->cellClass) = $this->get('Headings');
     $data = $model->getData();
     $nav = $model->getPagination();
     $c = 0;
     foreach ($data as $groupk => $group) {
         foreach ($group as $i => $x) {
             $o = new stdClass();
             if (is_object($data[$groupk])) {
                 $o->data = ArrayHelper::fromObject($data[$groupk]);
             } else {
                 $o->data = $data[$groupk][$i];
             }
             $o->cursor = $i + $nav->limitstart;
             $o->total = $nav->total;
             $o->id = 'list_' . $item->id . '_row_' . @$o->data->__pk_val;
             $o->class = "fabrik_row oddRow" . $c;
             if (is_object($data[$groupk])) {
                 $data[$groupk] = $o;
             } else {
                 $data[$groupk][$i] = $o;
             }
             $c = 1 - $c;
         }
     }
     // $$$ hugh - heading[3] doesn't exist any more?  Trying [0] instead.
     $d = array('id' => $item->id, 'rowid' => $rowid, 'model' => 'list', 'data' => $data, 'headings' => $this->headings, 'formid' => $model->getTable()->form_id, 'lastInsertedRow' => JFactory::getSession()->get('lastInsertedRow', 'test'));
     $d['nav'] = get_object_vars($nav);
     $d['htmlnav'] = $params->get('show-table-nav', 1) ? $nav->getListFooter($model->getId(), $this->getTmpl()) : '';
     $d['calculations'] = $model->getCalculations();
     $msg = $app->getMessageQueue();
     if (!empty($msg)) {
         $d['msg'] = $msg[0]['message'];
     }
     echo json_encode($d);
 }
Пример #8
0
 /**
  * Get a link to this element which will call onAjax_renderQRCode().
  *
  * @param   array|object  $thisRow  Row data
  *
  * @since 3.1
  *
  * @return   string  QR code link
  */
 protected function qrCodeLink($thisRow)
 {
     if (is_object($thisRow)) {
         $thisRow = ArrayHelper::fromObject($thisRow);
     }
     $formModel = $this->getFormModel();
     $formId = $formModel->getId();
     $rowId = $formModel->getRowId();
     if (empty($rowId)) {
         /**
          * Meh.  See commentary at the start of $formModel->getEmailData() about rowid.  For now, if this is a new row,
          * the only place we're going to find it is in the list model's lastInsertId.  Bah humbug.
          * But check __pk_val first anyway, what the heck.
          */
         $rowId = FArrayHelper::getValue($thisRow, '__pk_val', '');
         if (empty($rowId)) {
             /**
              * Nope.  Try lastInsertId. Or maybe on top of the fridge?  Or in the microwave?  Down the back
              * of the couch cushions?
              */
             $rowId = $formModel->getListModel()->lastInsertId;
             /**
              * OK, give up.  If *still* no rowid, we're probably being called from something like getEmailData() on onBeforeProcess or
              * onBeforeStore, and it's a new form, so no rowid yet.  So no point returning anything yet.
              */
             if (empty($rowId)) {
                 return '';
             }
         }
     }
     /*
      * YAY!!!  w00t!!  We have a rowid.  Whoop de freakin' doo!!
      */
     $elementId = $this->getId();
     $src = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $this->package . '&task=plugin.pluginAjax&plugin=field&method=ajax_renderQRCode&' . 'format=raw&element_id=' . $elementId . '&formid=' . $formId . '&rowid=' . $rowId . '&repeatcount=0';
     $layout = $this->getLayout('qr');
     $displayData = new stdClass();
     $displayData->src = $src;
     return $layout->render($displayData);
 }
Пример #9
0
 /**
  * Get edit row button label
  *
  * @param   object  $row  active table row
  *
  * @since   3.1rc1
  *
  * @return  string
  */
 public function editLabel($row)
 {
     $params = $this->getParams();
     $row = ArrayHelper::fromObject($row);
     return FText::_($this->parseMessageForRowHolder($params->get('editlabel', FText::_('COM_FABRIK_EDIT')), $row));
 }
Пример #10
0
 /**
  * If editing a record which contains repeated join data then on start $data is an
  * array with each records being a row in the database.
  *
  * We need to take this structure and convert it to the same format as when the form
  * is submitted
  *
  * @param   array  &$data  form data
  *
  * @return  void
  */
 public function setJoinData(&$data)
 {
     $this->_joinDefaultData = array();
     if (empty($data)) {
         return;
     }
     // No joins so leave !
     if (!is_array($this->aJoinObjs) || $this->rowId === '') {
         return;
     }
     if (!array_key_exists(0, $data)) {
         $data[0] = new stdClass();
     }
     $groups = $this->getGroupsHiarachy();
     /**
      * $$$ hugh - adding the "PK's seen" stuff, otherwise we end up adding multiple
      * rows when we have multiple repeat groups.  For instance, if we had two repeated
      * groups, one with 2 repeats and one with 3, we ended up with 6 repeats for each
      * group, with 3 and 2 copies of each respectively.  So we need to track which
      * instances of each repeat we have already copied into the main row.
      *
      * So $joinPksSeen will be indexed by $joinPksSeen[groupid][elementid]
      */
     $joinPksSeen = array();
     /**
      * Have to copy the data for the PK's seen stuff, as we're modifying the original $data
      * as we go, which screws up the PK logic once we've modified the PK value itself in the
      * original $data.  Probably only needed for $data[0], as that's the only row we actually
      * modify, but for now I'm just copying the whole thing, which then gets used for doing the ...
      * $joinPkVal = $data_copy[$row_index]->$joinPk;
      * ... inside the $data iteration below.
      *
      * PS, could probably just do a $data_copy = $data, as our usage of the copy isn't going to
      * involve nested arrays (which get copied by reference when using =), but I've been burned
      * so many times with array copying, I'm going to do a "deep copy" using serialize/unserialize!
      */
     $data_copy = unserialize(serialize($data));
     foreach ($groups as $groupId => $groupModel) {
         $group = $groupModel->getGroup();
         $joinPksSeen[$groupId] = array();
         $elementModels = $groupModel->getMyElements();
         foreach ($elementModels as $elementModelID => $elementModel) {
             if ($groupModel->isJoin() || $elementModel->isJoin()) {
                 if ($groupModel->isJoin()) {
                     $joinModel = $groupModel->getJoinModel();
                     $joinPk = $joinModel->getForeignID();
                     $joinPksSeen[$groupId][$elementModelID] = array();
                 }
                 $names = $elementModel->getJoinDataNames();
                 foreach ($data as $row_index => $row) {
                     // Might be a string if new record ?
                     $row = (object) $row;
                     if ($groupModel->isJoin()) {
                         /**
                          * If the join's PK element isn't published or for any other reason not
                          * in $data, we're hosed!
                          */
                         if (!isset($data_copy[$row_index]->{$joinPk})) {
                             continue;
                         }
                         $joinPkVal = $data_copy[$row_index]->{$joinPk};
                         /**
                          * if we've seen the PK value for this element's row before, skip it.
                          * Check for empty as well, just in case - as we're loading existing data,
                          * it darn well should have a value!
                          */
                         if (empty($joinPkVal) || in_array($joinPkVal, $joinPksSeen[$groupId][$elementModelID])) {
                             continue;
                         }
                     }
                     for ($i = 0; $i < count($names); $i++) {
                         $name = $names[$i];
                         if (array_key_exists($name, $row)) {
                             $v = $row->{$name};
                             $v = FabrikWorker::JSONtoData($v, $elementModel->isJoin());
                             // New record or csv export
                             if (!isset($data[0]->{$name})) {
                                 $data[0]->{$name} = $v;
                             }
                             if (!is_array($data[0]->{$name})) {
                                 if ($groupModel->isJoin() && $groupModel->canRepeat()) {
                                     $v = array($v);
                                 }
                                 $data[0]->{$name} = $v;
                             } else {
                                 if ($groupModel->isJoin() && $groupModel->canRepeat()) {
                                     $n =& $data[0]->{$name};
                                     $n[] = $v;
                                 }
                             }
                         }
                     }
                     if ($groupModel->isJoin()) {
                         /**
                          * Make a Note To Self that we've now handled the data for this element's row,
                          * and can skip it from now on.
                          */
                         $joinPksSeen[$groupId][$elementModelID][] = $joinPkVal;
                     }
                 }
             }
         }
     }
     // Remove the additional rows - they should have been merged into [0] above. if no [0] then use main array
     $data = ArrayHelper::fromObject(FArrayHelper::getValue($data, 0, $data));
 }
Пример #11
0
 protected function doAdd($data)
 {
     if (empty($this->list_route)) {
         throw new \Exception('Must define a route for listing the items');
     }
     if (empty($this->create_item_route)) {
         throw new \Exception('Must define a route for creating the item');
     }
     if (empty($this->edit_item_route)) {
         throw new \Exception('Must define a route for editing the item');
     }
     if (!isset($data['submitType'])) {
         $data['submitType'] = "save_edit";
     }
     $f3 = \Base::instance();
     $flash = \Dsc\Flash::instance();
     $model = $this->getModel();
     // save
     try {
         $values = $data;
         $create = array_filter($values['stripe']);
         //make a method for this, convert float to cents
         $create['amount'] = (int) $create['amount'];
         $settings = \Striper\Models\Settings::fetch();
         // Set your secret key: remember to change this to your live secret key in production
         // See your keys here https://manage.stripe.com/account
         \Stripe\Stripe::setApiKey($settings->{$settings->mode . '.secret_key'});
         $plan = \Stripe\Plan::create($create);
         $values['stripe'] = array('id' => $plan->id, 'name' => $plan->name, 'created' => $plan->created, 'amount' => $plan->amount, 'interval' => $plan->interval, 'currency' => $plan->currency, 'interval_count' => $plan->interval_count, 'trial_period_days' => $plan->trial_period_days);
         unset($values['submitType']);
         //\Dsc\System::instance()->addMessage(\Dsc\Debug::dump($values), 'warning');
         $this->item = $model->create($values);
     } catch (\Exception $e) {
         \Dsc\System::instance()->addMessage('Save failed with the following errors:', 'error');
         \Dsc\System::instance()->addMessage($e->getMessage(), 'error');
         if (\Base::instance()->get('DEBUG')) {
             \Dsc\System::instance()->addMessage($e->getTraceAsString(), 'error');
         }
         if ($f3->get('AJAX')) {
             // output system messages in response object
             return $this->outputJson($this->getJsonResponse(array('error' => true, 'message' => \Dsc\System::instance()->renderMessages())));
         }
         // redirect back to the create form with the fields pre-populated
         \Dsc\System::instance()->setUserState('use_flash.' . $this->create_item_route, true);
         $flash->store($data);
         $this->setRedirect($this->create_item_route);
         return false;
     }
     // redirect to the editing form for the new item
     \Dsc\System::instance()->addMessage('Item saved', 'success');
     if (method_exists($this->item, 'cast')) {
         $this->item_data = $this->item->cast();
     } else {
         $this->item_data = \Joomla\Utilities\ArrayHelper::fromObject($this->item);
     }
     if ($f3->get('AJAX')) {
         return $this->outputJson($this->getJsonResponse(array('message' => \Dsc\System::instance()->renderMessages(), 'result' => $this->item_data)));
     }
     switch ($data['submitType']) {
         case "save_new":
             $route = $this->create_item_route;
             break;
         case "save_close":
             $route = $this->list_route;
             break;
         default:
             $flash->store($this->item_data);
             $id = $this->item->get($this->getItemKey());
             $route = str_replace('{id}', $id, $this->edit_item_route);
             break;
     }
     $this->setRedirect($route);
     return $this;
 }
Пример #12
0
 /**
  * Can the row be edited
  *
  * @param   object  $row  Current row to test
  *
  * @return boolean
  */
 public function onCanEdit($row)
 {
     $params = $this->getParams();
     // If $row is null, we were called from the list's canEdit() in a per-table rather than per-row context,
     // and we don't have an opinion on per-table edit permissions, so just return true.
     if (is_null($row) || is_null($row[0])) {
         return true;
     }
     if (is_array($row[0])) {
         $data = ArrayHelper::toObject($row[0]);
     } else {
         $data = $row[0];
     }
     /**
      * If __pk_val is not set or empty, then we've probably been called from somewhere in form processing,
      * and this is a new row.  In which case this plugin cannot offer any opinion!
      */
     if (!isset($data->__pk_val) || empty($data->__pk_val)) {
         return true;
     }
     $field = str_replace('.', '___', $params->get('caneditrow_field'));
     // If they provided some PHP to eval, we ignore the other settings and just run their code
     $caneditrow_eval = $params->get('caneditrow_eval', '');
     // $$$ rob if no can edit field selected in admin return true
     if (trim($field) == '' && trim($caneditrow_eval) == '') {
         $this->acl[$data->__pk_val] = true;
         return true;
     }
     if (!empty($caneditrow_eval)) {
         $w = new FabrikWorker();
         $data = ArrayHelper::fromObject($data);
         $caneditrow_eval = $w->parseMessageForPlaceHolder($caneditrow_eval, $data);
         FabrikWorker::clearEval();
         $caneditrow_eval = @eval($caneditrow_eval);
         FabrikWorker::logEval($caneditrow_eval, 'Caught exception on eval in can edit row : %s');
         $this->acl[$data['__pk_val']] = $caneditrow_eval;
         return $caneditrow_eval;
     } else {
         // No PHP given, so just do a simple match on the specified element and value settings.
         if ($params->get('caneditrow_useraw', '0') == '1') {
             $field .= '_raw';
         }
         $value = $params->get('caneditrow_value');
         $operator = $params->get('operator', '=');
         if (is_object($data->{$field})) {
             $data->{$field} = ArrayHelper::fromObject($data->{$field});
         }
         switch ($operator) {
             case '=':
             default:
                 $return = is_array($data->{$field}) ? in_array($value, $data->{$field}) : $data->{$field} == $value;
                 break;
             case "!=":
                 $return = is_array($data->{$field}) ? !in_array($value, $data->{$field}) : $data->{$field} != $value;
                 break;
         }
         $this->acl[$data->__pk_val] = $return;
         return $return;
     }
 }
Пример #13
0
 /**
  * Access control function for determining if the user can perform
  * a designated function on a specific row
  *
  * @param   object $params Item params to test
  * @param   object $row    Data
  * @param   string $col    Access control setting to compare against
  *
  * @return    mixed    - if ACL setting defined here return bool, otherwise return -1 to continue with default acl
  *                     setting
  */
 public static function canUserDo($params, $row, $col)
 {
     if (!is_null($row)) {
         $app = JFactory::getApplication();
         $input = $app->input;
         $user = JFactory::getUser();
         $userCol = $params->get($col, '');
         if ($userCol != '') {
             $userCol = FabrikString::safeColNameToArrayKey($userCol);
             if (!array_key_exists($userCol, $row)) {
                 return false;
             } else {
                 if (array_key_exists($userCol . '_raw', $row)) {
                     $userCol .= '_raw';
                 }
                 $myId = $user->get('id');
                 // -1 for menu items that link to their own records
                 $userColVal = is_array($row) ? $row[$userCol] : $row->{$userCol};
                 // User element stores as object
                 if (is_object($userColVal)) {
                     $userColVal = ArrayHelper::fromObject($userColVal);
                 }
                 // Could be coming back from a failed validation in which case val might be an array
                 if (is_array($userColVal)) {
                     $userColVal = array_shift($userColVal);
                 }
                 if (empty($userColVal) && empty($myId)) {
                     return false;
                 }
                 if (intVal($userColVal) === intVal($myId) || $input->get('rowid') == -1) {
                     return true;
                 }
             }
         }
     }
     return -1;
 }
Пример #14
0
 /**
  * Run right at the end of the form processing
  * form needs to be set to record in database for this to hook to be called
  *
  * @return	bool
  */
 public function onAfterProcess()
 {
     $params = $this->getParams();
     $formModel = $this->getModel();
     $input = $this->app->input;
     $this->data = $this->getProcessData();
     JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_fabrik/tables');
     if (!$this->shouldProcess('paypal_conditon', null, $params)) {
         return true;
     }
     $w = new FabrikWorker();
     $userId = $this->user->get('id');
     $ipn = $this->getIPNHandler($params);
     if ($ipn !== false) {
         if (method_exists($ipn, 'createInvoice')) {
             $ipn->createInvoice();
         }
     }
     $testMode = $params->get('paypal_testmode', $input->get('paypal_testmode', false));
     $url = $testMode == 1 ? 'https://www.sandbox.paypal.com/us/cgi-bin/webscr?' : 'https://www.paypal.com/cgi-bin/webscr?';
     $opts = array();
     $opts['cmd'] = $params->get('paypal_cmd', "_xclick");
     $email = $testMode ? 'paypal_accountemail_testmode' : 'paypal_accountemail';
     $email = $params->get($email);
     if (trim($email) == '') {
         $email = $this->data[FabrikString::safeColNameToArrayKey($params->get('paypal_accountemail_element'))];
         if (is_array($email)) {
             $email = array_shift($email);
         }
     }
     $opts['business'] = $email;
     $amount = $params->get('paypal_cost');
     $amount = $w->parseMessageForPlaceHolder($amount, $this->data);
     /**
      * Adding eval option on cost field
      * Useful if you use a cart system which will calculate on total shipping or tax fee and apply it. You can return it in the Cost field.
      * Returning false will log an error and bang out with a runtime exception.
      */
     if ($params->get('paypal_cost_eval', 0) == 1) {
         $amount = @eval($amount);
         if ($amount === false) {
             $msgType = 'fabrik.paypal.onAfterProcess';
             $msg = new stdClass();
             $msg->opt = $opts;
             $msg->data = $this->data;
             $msg->msg = "Eval amount code returned false.";
             $msg = json_encode($msg);
             $this->doLog($msgType, $msg);
             throw new RuntimeException(FText::_('PLG_FORM_PAYPAL_COST_ELEMENT_ERROR'), 500);
         }
     }
     if (trim($amount) == '') {
         // Priority to raw data.
         $amountKey = FabrikString::safeColNameToArrayKey($params->get('paypal_cost_element'));
         $amount = FArrayHelper::getValue($this->data, $amountKey);
         $amount = FArrayHelper::getValue($this->data, $amountKey . '_raw', $amount);
         if (is_array($amount)) {
             $amount = array_shift($amount);
         }
     }
     $opts['amount'] = $amount;
     // $$$tom added Shipping Cost params
     $shippingAmount = $params->get('paypal_shipping_cost');
     if ($params->get('paypal_shipping_cost_eval', 0) == 1) {
         $shippingAmount = @eval($shippingAmount);
     }
     if (trim($shippingAmount) == '') {
         $shippingAmount = FArrayHelper::getValue($this->data, FabrikString::safeColNameToArrayKey($params->get('paypal_shipping_cost_element')));
         if (is_array($shippingAmount)) {
             $shippingAmount = array_shift($shippingAmount);
         }
     }
     $opts['shipping'] = "{$shippingAmount}";
     $item = $params->get('paypal_item');
     $item = $w->parseMessageForPlaceHolder($item, $this->data);
     if ($params->get('paypal_item_eval', 0) == 1) {
         $item = @eval($item);
         $itemRaw = $item;
     }
     if (trim($item) == '') {
         $itemRaw = FArrayHelper::getValue($this->data, FabrikString::safeColNameToArrayKey($params->get('paypal_item_element') . '_raw'));
         $item = $this->data[FabrikString::safeColNameToArrayKey($params->get('paypal_item_element'))];
         if (is_array($item)) {
             $item = array_shift($item);
         }
         if (is_array($itemRaw)) {
             $itemRaw = array_shift($itemRaw);
         }
     }
     // $$$ hugh - strip any HTML tags from the item name, as PayPal doesn't like them.
     $opts['item_name'] = strip_tags($item);
     // $$$ rob add in subscription variables
     if ($this->isSubscription($params)) {
         $subTable = JModelLegacy::getInstance('List', 'FabrikFEModel');
         $subTable->setId((int) $params->get('paypal_subs_table'));
         $idEl = FabrikString::safeColName($params->get('paypal_subs_id', ''));
         $durationEl = FabrikString::safeColName($params->get('paypal_subs_duration', ''));
         $durationPerEl = FabrikString::safeColName($params->get('paypal_subs_duration_period', ''));
         $name = $params->get('paypal_subs_name', '');
         $subDb = $subTable->getDb();
         $query = $subDb->getQuery(true);
         $query->select('*, ' . $durationEl . ' AS p3, ' . $durationPerEl . ' AS t3, ' . $subDb->q($itemRaw) . ' AS item_number')->from($subTable->getTable()->db_table_name)->where($idEl . ' = ' . $subDb->quote($itemRaw));
         $subDb->setQuery($query);
         $sub = $subDb->loadObject();
         if (is_object($sub)) {
             $opts['p3'] = $sub->p3;
             $opts['t3'] = $sub->t3;
             $opts['a3'] = $amount;
             $opts['no_note'] = 1;
             $opts['custom'] = '';
             $filter = JFilterInput::getInstance();
             $post = $filter->clean($_POST, 'array');
             $tmp = array_merge($post, ArrayHelper::fromObject($sub));
             // 'http://fabrikar.com/ '.$sub->item_name.' - User: subtest26012010 (subtest26012010)';
             $opts['item_name'] = $w->parseMessageForPlaceHolder($name, $tmp);
             $opts['invoice'] = $w->parseMessageForPlaceHolder($params->get('paypal_subs_invoice'), $tmp, false);
             if ($opts['invoice'] == '') {
                 $opts['invoice'] = uniqid('', true);
             }
             $opts['src'] = $w->parseMessageForPlaceHolder($params->get('paypal_subs_recurring'), $tmp);
             $amount = $opts['amount'];
             unset($opts['amount']);
         } else {
             throw new RuntimeException('Could not determine subscription period, please check your settings', 500);
         }
     }
     if (!$this->isSubscription($params)) {
         // Reset the amount which was unset during subscription code
         $opts['amount'] = $amount;
         $opts['cmd'] = '_xclick';
         // Unset any subscription options we may have set
         unset($opts['p3']);
         unset($opts['t3']);
         unset($opts['a3']);
         unset($opts['no_note']);
     }
     $shipping_table = $this->shippingTable();
     if ($shipping_table !== false) {
         $thisTable = $formModel->getListModel()->getTable()->db_table_name;
         $shippingUserId = $userId;
         /*
          * If the shipping table is the same as the form's table, and no user logged in
          * then use the shipping data entered into the form:
          * see http://fabrikar.com/forums/index.php?threads/paypal-shipping-address-without-joomla-userid.33229/
          */
         if ($shippingUserId === 0 && $thisTable === $shipping_table) {
             $shippingUserId = $formModel->formData['id'];
         }
         if ($shippingUserId > 0) {
             $shippingSelect = array();
             $db = FabrikWorker::getDbo();
             $query = $db->getQuery(true);
             if ($params->get('paypal_shippingdata_firstname')) {
                 $shippingFirstName = FabrikString::shortColName($params->get('paypal_shippingdata_firstname'));
                 $shippingSelect['first_name'] = $shippingFirstName;
             }
             if ($params->get('paypal_shippingdata_lastname')) {
                 $shippingLastName = FabrikString::shortColName($params->get('paypal_shippingdata_lastname'));
                 $shippingSelect['last_name'] = $shippingLastName;
             }
             if ($params->get('paypal_shippingdata_address1')) {
                 $shippingAddress1 = FabrikString::shortColName($params->get('paypal_shippingdata_address1'));
                 $shippingSelect['address1'] = $shippingAddress1;
             }
             if ($params->get('paypal_shippingdata_address2')) {
                 $shippingAddress2 = FabrikString::shortColName($params->get('paypal_shippingdata_address2'));
                 $shippingSelect['address2'] = $shippingAddress2;
             }
             if ($params->get('paypal_shippingdata_zip')) {
                 $shippingZip = FabrikString::shortColName($params->get('paypal_shippingdata_zip'));
                 $shippingSelect['zip'] = $shippingZip;
             }
             if ($params->get('paypal_shippingdata_state')) {
                 $shippingState = FabrikString::shortColName($params->get('paypal_shippingdata_state'));
                 $shippingSelect['state'] = $shippingState;
             }
             if ($params->get('paypal_shippingdata_city')) {
                 $shippingCity = FabrikString::shortColName($params->get('paypal_shippingdata_city'));
                 $shippingSelect['city'] = $shippingCity;
             }
             if ($params->get('paypal_shippingdata_country')) {
                 $shippingCountry = FabrikString::shortColName($params->get('paypal_shippingdata_country'));
                 $shippingSelect['country'] = $shippingCountry;
             }
             $query->clear();
             if (empty($shippingSelect) || $shipping_table == '') {
                 $this->app->enqueueMessage('No shipping lookup table or shipping fields selected');
             } else {
                 $query->select($shippingSelect)->from($shipping_table)->where(FabrikString::shortColName($params->get('paypal_shippingdata_id')) . ' = ' . $db->q($shippingUserId));
                 $db->setQuery($query);
                 $userShippingData = $db->loadObject();
                 foreach ($shippingSelect as $opt => $val) {
                     // $$$tom Since we test on the current userid, it always adds the &name=&street=....
                     // Even if those vars are empty...
                     if ($val) {
                         $opts[$opt] = $userShippingData->{$val};
                     }
                 }
             }
         }
     }
     if ($params->get('paypal_shipping_address_override', 0)) {
         $opts['address_override'] = 1;
     }
     $currencyCode = $params->get('paypal_currencycode', 'USD');
     $currencyCode = $w->parseMessageForPlaceHolder($currencyCode, $this->data);
     $opts['currency_code'] = $currencyCode;
     $testSite = $params->get('paypal_test_site', '');
     $testSite = rtrim($testSite, '/');
     if ($testMode == 1 && !empty($testSite)) {
         $ppurl = $testSite . '/index.php?option=com_' . $this->package . '&c=plugin&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=ipn';
     } else {
         $ppurl = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $this->package . '&c=plugin&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=ipn';
     }
     $testSite_qs = $params->get('paypal_test_site_qs', '');
     if ($testMode == 1 && !empty($testSite_qs)) {
         $ppurl .= $testSite_qs;
     }
     $ppurl .= '&renderOrder=' . $this->renderOrder;
     $ppurl = urlencode($ppurl);
     $opts['notify_url'] = "{$ppurl}";
     $paypal_return_url = $params->get('paypal_return_url', '');
     $paypal_return_url = $w->parseMessageForPlaceHolder($paypal_return_url, $this->data);
     if ($testMode == 1 && !empty($paypal_return_url)) {
         if (preg_match('#^http:\\/\\/#', $paypal_return_url)) {
             $opts['return'] = $paypal_return_url;
         } else {
             if (!empty($testSite)) {
                 $opts['return'] = $testSite . '/' . $paypal_return_url;
             } else {
                 $opts['return'] = COM_FABRIK_LIVESITE . $paypal_return_url;
             }
         }
         if (!empty($testSite_qs)) {
             $opts['return'] .= $testSite_qs;
         }
     } elseif (!empty($paypal_return_url)) {
         if (preg_match('#^http:\\/\\/#', $paypal_return_url)) {
             $opts['return'] = $paypal_return_url;
         } else {
             $opts['return'] = COM_FABRIK_LIVESITE . $paypal_return_url;
         }
     } else {
         // Using default thanks() method so don't forget to add renderOrder
         if ($testMode == '1' && !empty($testSite)) {
             $opts['return'] = $testSite . '/index.php?option=com_' . $this->package . '&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=thanks&rowid=' . $this->data['rowid'] . '&renderOrder=' . $this->renderOrder;
         } else {
             $opts['return'] = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $this->package . '&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=thanks&rowid=' . $this->data['rowid'] . '&renderOrder=' . $this->renderOrder;
         }
     }
     $opts['return'] = urlencode($opts['return']);
     $ipnValue = $params->get('paypal_ipn_value', '');
     $ipnValue = $w->parseMessageForPlaceHolder($ipnValue, $this->data);
     // Extra :'s will break parsing during IPN notify phase
     $ipnValue = str_replace(':', ';', $ipnValue);
     // $$$ hugh - thinking about putting in a call to a generic method in custom script
     // here and passing it a reference to $opts.
     if ($ipn !== false) {
         if (method_exists($ipn, 'checkOpts')) {
             if ($ipn->checkOpts($opts, $formModel) === false) {
                 // Log the info
                 $msgType = 'fabrik.paypal.onAfterProcess';
                 $msg = new stdClass();
                 $msg->opt = $opts;
                 $msg->data = $this->data;
                 $msg->msg = "Submission cancelled by checkOpts!";
                 $msg = json_encode($msg);
                 $this->doLog($msgType, $msg);
                 return true;
             }
         }
     }
     $opts['custom'] = $this->data['formid'] . ':' . $this->data['rowid'] . ':' . $ipnValue;
     $qs = array();
     foreach ($opts as $k => $v) {
         $qs[] = "{$k}={$v}";
     }
     $url .= implode('&', $qs);
     $this->setDelayedRedirect($url);
     // Log the info
     $msgType = 'fabrik.paypal.onAfterProcess';
     $msg = new stdClass();
     $msg->opt = $opts;
     $msg->data = $this->data;
     $msg = json_encode($msg);
     $this->doLog($msgType, $msg);
     return true;
 }
Пример #15
0
 /**
  * Method to unset the root_user value from configuration data.
  *
  * This method will load the global configuration data straight from
  * JConfig and remove the root_user value for security, then save the configuration.
  *
  * @return	boolean  True on success, false on failure.
  *
  * @since	1.6
  */
 public function removeroot()
 {
     // Get the previous configuration.
     $prev = new JConfig();
     $prev = ArrayHelper::fromObject($prev);
     // Create the new configuration object, and unset the root_user property
     unset($prev['root_user']);
     $config = new Registry($prev);
     // Write the configuration file.
     return $this->writeConfigFile($config);
 }
Пример #16
0
 /**
  * Get the map icons
  *
  * @return  array
  */
 public function getJSIcons()
 {
     $input = $this->app->input;
     $icons = array();
     $w = new FabrikWorker();
     $uri = JURI::getInstance();
     $params = $this->getParams();
     $templates = (array) $params->get('fb_gm_detailtemplate');
     $templates_nl2br = (array) $params->get('fb_gm_detailtemplate_nl2br');
     $listIds = (array) $params->get('googlemap_table');
     // Images for file system
     $aIconImgs = (array) $params->get('fb_gm_iconimage');
     // Image from marker data
     $markerImages = (array) $params->get('fb_gm_iconimage2');
     $markerImagesPath = (array) $params->get('fb_gm_iconimage2_path');
     // Specified letter
     $letters = (array) $params->get('fb_gm_icon_letter');
     $aFirstIcons = (array) $params->get('fb_gm_first_iconimage');
     $aLastIcons = (array) $params->get('fb_gm_last_iconimage');
     $titleElements = (array) $params->get('fb_gm_title_element');
     $radiusElements = (array) $params->get('fb_gm_radius_element');
     $radiusDefaults = (array) $params->get('fb_gm_radius_default');
     $radiusUnits = (array) $params->get('fb_gm_radius_unit');
     $groupClass = (array) $params->get('fb_gm_group_class');
     $c = 0;
     $this->recordCount = 0;
     $maxMarkers = $params->get('fb_gm_markermax', 0);
     $recLimit = count($listIds) == 1 ? $maxMarkers : 0;
     $limitMessageShown = false;
     $limitMessage = $params->get('fb_gm_markermax_message');
     $groupedIcons = array();
     $lc = 0;
     foreach ($listIds as $listId) {
         $listModel = $this->getlistModel($listId);
         $template = FArrayHelper::getValue($templates, $c, '');
         /**
          * One day we should get smarter about how we decide which elements to render
          * but for now all we can do is set formatAll(), in case they use an element
          * which isn't set for list display, which then wouldn't get rendered unless we do this.
          */
         if (FabrikString::usesElementPlaceholders($template)) {
             $listModel->formatAll(true);
         }
         $template_nl2br = FArrayHelper::getValue($templates_nl2br, $c, '1') == '1';
         $mapsElements = FabrikHelperList::getElements($listModel, array('plugin' => 'googlemap', 'published' => 1));
         $coordColumn = $mapsElements[0]->getFullName(true, false) . "_raw";
         // Are we using random start location for icons?
         $listModel->_randomRecords = $params->get('fb_gm_random_marker') == 1 && $recLimit != 0 ? true : false;
         // Used in list model setLimits
         $input->set('limit' . $listId, $recLimit);
         $listModel->setLimits();
         $listModel->getPagination(0, 0, $recLimit);
         $data = $listModel->getData();
         $this->txt = array();
         $k = 0;
         foreach ($data as $groupKey => $group) {
             foreach ($group as $row) {
                 $customImageFound = false;
                 $iconImg = FArrayHelper::getValue($aIconImgs, $c, '');
                 if ($k == 0) {
                     $firstIcon = FArrayHelper::getValue($aFirstIcons, $c, $iconImg);
                     if ($firstIcon !== '') {
                         $iconImg = $firstIcon;
                     }
                 }
                 if (!empty($iconImg)) {
                     $iconImg = '/media/com_fabrik/images/' . $iconImg;
                 }
                 $v = $this->getCordsFromData($row->{$coordColumn});
                 if ($v == array(0, 0)) {
                     // Don't show icons with no data
                     continue;
                 }
                 $rowData = ArrayHelper::fromObject($row);
                 $rowData['rowid'] = $rowData['__pk_val'];
                 $rowData['coords'] = $v[0] . ',' . $v[1];
                 $rowData['nav_url'] = "http://maps.google.com/maps?q=loc:" . $rowData['coords'] . "&navigate=yes";
                 $html = $w->parseMessageForPlaceHolder($template, $rowData);
                 FabrikHelperHTML::runContentPlugins($html);
                 $titleElement = FArrayHelper::getValue($titleElements, $c, '');
                 $title = $titleElement == '' ? '' : html_entity_decode(strip_tags($row->{$titleElement}), ENT_COMPAT, 'UTF-8');
                 /* $$$ hugh - if they provided a template, lets assume they will handle the link themselves.
                  * http://fabrikar.com/forums/showthread.php?p=41550#post41550
                  * $$$ hugh - at some point the fabrik_view / fabrik_edit links became optional
                  */
                 if (empty($html) && (array_key_exists('fabrik_view', $rowData) || array_key_exists('fabrik_edit', $rowData))) {
                     // Don't insert line break in empty bubble without links $html .= "<br />";
                     // Use edit link by preference
                     if (array_key_exists('fabrik_edit', $rowData)) {
                         if ($rowData['fabrik_edit'] != '') {
                             $html .= "<br />";
                         }
                         $html .= $rowData['fabrik_edit'];
                     } else {
                         if ($rowData['fabrik_view'] != '') {
                             $html .= "<br />";
                         }
                         $html .= $rowData['fabrik_view'];
                     }
                 }
                 if ($template_nl2br) {
                     /*
                      *  $$$ hugh - not sure why we were doing this rather than nl2br?
                      If there was a reason, this is still broken, as it ends up inserting
                      two breaks.  So if we can't use nl2br ... I need fix this before using it again!
                     
                     $html = str_replace(array("\n\r"), "<br />", $html);
                     $html = str_replace(array("\r\n"), "<br />", $html);
                     $html = str_replace(array("\n", "\r"), "<br />", $html);
                     */
                     $html = nl2br($html);
                 }
                 $html = str_replace("'", '"', $html);
                 $this->txt[] = $html;
                 if ($iconImg == '') {
                     $iconImg = FArrayHelper::getValue($markerImages, $c, '');
                     if ($iconImg != '') {
                         /**
                          * $$$ hugh - added 'path' choice for data icons, to make this option more flexible.  Up till
                          * now we have been forcing paths relative to /media/com_fabrik/images (which was added in the JS).
                          * New options for path root are:
                          *
                          * media - (default) existing behavior of /meadia/com_fabrik/images
                          * jroot - relative to J! root
                          * absolute - full server path
                          * url - url (surprise surprise)
                          * img - img tag (so we extract src=)
                          */
                         $iconImgPath = FArrayHelper::getValue($markerImagesPath, $c, 'media');
                         $iconImg = FArrayHelper::getValue($rowData, $iconImg, '');
                         // Normalize the $iconimg so it is either a file path relative to J! root, or a non-local URL
                         switch ($iconImgPath) {
                             case 'media':
                             default:
                                 $iconImg = 'media/com_fabrik/images' . $iconImg;
                                 break;
                             case 'jroot':
                                 break;
                             case 'absolute':
                                 $iconImg = str_replace(JPATH_BASE, '', $iconImg);
                                 break;
                             case 'url':
                                 $iconImg = str_replace(COM_FABRIK_LIVESITE, '', $iconImg);
                                 break;
                             case 'img':
                                 // Get the src
                                 preg_match('/src=["|\'](.*?)["|\']/', $iconImg, $matches);
                                 if (array_key_exists(1, $matches)) {
                                     $iconImg = $matches[1];
                                 }
                                 $iconImg = str_replace(COM_FABRIK_LIVESITE, '', $iconImg);
                                 break;
                         }
                         if (strstr($iconImg, 'http://') || strstr($iconImg, 'https://') || JFile::exists(JPATH_BASE . $iconImg)) {
                             $customImageFound = true;
                         }
                     }
                     if ($iconImg != '' && !(strstr($iconImg, 'http://') || strstr($iconImg, 'https://'))) {
                         list($width, $height) = $this->markerSize(JPATH_BASE . $iconImg);
                     } else {
                         // Standard google map icon size
                         $width = 20;
                         $height = 34;
                     }
                 } else {
                     // Standard google map icon size
                     list($width, $height) = $this->markerSize(JPATH_BASE . $iconImg);
                 }
                 $gClass = FArrayHelper::getValue($groupClass, 0, '');
                 if (!empty($gClass)) {
                     $gClass .= '_raw';
                     $gClass = isset($row->{$gClass}) ? $row->{$gClass} : '';
                 }
                 if (array_key_exists($v[0] . $v[1], $icons)) {
                     $existingIcon = $icons[$v[0] . $v[1]];
                     if ($existingIcon['groupkey'] == $groupKey) {
                         /* $$$ hugh - this inserts label between multiple record $html, but not at the top.
                          * If they want to insert label, they can do it themselves in the template.
                          * $icons[$v[0].$v[1]][2] = $icons[$v[0].$v[1]][2] . "<h6>$table->label</h6>" . $html;
                          * Don't insert linebreaks in empty bubble
                          */
                         if ($html != '') {
                             $html = "<br />" . $html;
                         }
                         $icons[$v[0] . $v[1]][2] = $icons[$v[0] . $v[1]][2] . $html;
                         if ($customImageFound) {
                             $icons[$v[0] . $v[1]][3] = $iconImg;
                         }
                     } else {
                         $groupedIcons[] = array($v[0], $v[1], $html, $iconImg, $width, $height, 'groupkey' => $groupKey, 'listid' => $listId, 'title' => $title, 'groupClass' => 'type' . $gClass);
                     }
                 } else {
                     // Default icon - lets see if we need to use a letter icon instead
                     if (FArrayHelper::getValue($letters, $c, '') != '') {
                         $iconImg = $uri->getScheme() . '://www.google.com/mapfiles/marker' . JString::strtoupper($letters[$c]) . '.png';
                     }
                     $icons[$v[0] . $v[1]] = array($v[0], $v[1], $html, $iconImg, $width, $height, 'groupkey' => $groupKey, 'listid' => $listId, 'title' => $title, 'groupClass' => 'type' . $gClass);
                 }
                 if ($params->get('fb_gm_use_radius', '0') == '1') {
                     $radiusElement = FArrayHelper::getValue($radiusElements, $c, '');
                     $radiusUnits = FArrayHelper::getValue($radiusUnits, $c, 'k');
                     $radiusMeters = $radiusUnits == 'k' ? 1000 : 1609.34;
                     if (!empty($radiusElement)) {
                         $radius = (double) $row->{$radiusElement};
                         $radius *= $radiusMeters;
                         $icons[$v[0] . $v[1]]['radius'] = $radius;
                     } else {
                         $default = (double) ArrayHelper::getvalue($radiusDefaults, $c, 50);
                         $default *= $radiusMeters;
                         $icons[$v[0] . $v[1]]['radius'] = $default;
                     }
                 }
                 $icons[$v[0] . $v[1]]['c'] = $c;
                 $this->recordCount++;
                 $k++;
             }
         }
         // Replace last icon?
         $iconImg = FArrayHelper::getValue($aLastIcons, $c, '');
         if ($iconImg != '' && !empty($icons)) {
             list($width, $height) = $this->markerSize(JPATH_SITE . '/media/com_fabrik/images/' . $iconImg);
             $icons[$v[0] . $v[1]][3] = '/media/com_fabrik/images/' . $iconImg;
             $icons[$v[0] . $v[1]][4] = $width;
             $icons[$v[0] . $v[1]][5] = $height;
         }
         $c++;
     }
     // Replace coord keys with numeric keys
     $icons = array_values($icons);
     $icons = array_merge($icons, $groupedIcons);
     if ($maxMarkers != 0 && $maxMarkers < count($icons)) {
         $icons = array_slice($icons, -$maxMarkers);
     }
     $limitMessageShown = !($k >= $recLimit);
     if (!$limitMessageShown && $recLimit !== 0 && $limitMessage != '') {
         $this->app->enqueueMessage($limitMessage);
     }
     FabrikHelperHTML::debug($icons, 'map');
     return $icons;
 }
Пример #17
0
 /**
  * Shows the data formatted for the list view
  *
  * @param   string    $data      Elements data
  * @param   stdClass  &$thisRow  All the data in the lists current row
  * @param   array     $opts      Rendering options
  *
  * @return  string	formatted value
  */
 public function renderListData($data, stdClass &$thisRow, $opts = array())
 {
     unset($this->default);
     $value = $this->getValue(ArrayHelper::fromObject($thisRow));
     return parent::renderListData($value, $thisRow, $opts);
 }
Пример #18
0
 /**
  * Build the item link
  *
  * @param   object  $listModel  list model
  * @param   object  $row        current row
  * @param   int     $c          which data set are we in (needed for getting correct params data)
  *
  * @return  string  url
  */
 protected function getLinkURL($listModel, $row, $c)
 {
     $w = new FabrikWorker();
     $params = $this->getParams();
     $customLink = (array) $params->get('timeline_customlink');
     $customLink = FArrayHelper::getValue($customLink, $c, '');
     if ($customLink !== '') {
         $url = @$w->parseMessageForPlaceHolder($customLink, ArrayHelper::fromObject($row), false, true);
         $url = str_replace('{rowid}', $row->__pk_val, $url);
     } else {
         $nextView = $listModel->canEdit() ? "form" : "details";
         $table = $listModel->getTable();
         if ($this->app->isAdmin()) {
             $url = 'index.php?option=com_fabrik&task=' . $nextView . '.view&formid=' . $table->form_id . '&rowid=' . $row->__pk_val;
         } else {
             $url = 'index.php?option=com_' . $this->package . '&view=' . $nextView . '&formid=' . $table->form_id . '&rowid=' . $row->__pk_val . '&listid=' . $listModel->getId();
         }
     }
     return $url;
 }
Пример #19
0
 /**
  * Draws the html form element
  *
  * @param   array  $data           to pre-populate element with
  * @param   int    $repeatCounter  repeat group counter
  *
  * @return  string	elements html
  */
 public function render($data, $repeatCounter = 0)
 {
     $name = $this->getHTMLName($repeatCounter);
     $id = $this->getHTMLId($repeatCounter);
     $params = $this->getParams();
     $bits = $this->inputProperties($repeatCounter);
     $value = $this->getValue($data, $repeatCounter);
     $opts = array();
     if ($value == '') {
         $value = array('label' => '', 'link' => '');
     } else {
         if (!is_array($value)) {
             $value = FabrikWorker::JSONtoData($value, true);
             /**
              * In some legacy case, data is like ...
              * [{"label":"foo","link":"bar"}]
              * ... I think if it came from 2.1.  So lets check to see if we need
              * to massage that into the right format
              */
             if (array_key_exists(0, $value) && is_object($value[0])) {
                 $value = ArrayHelper::fromObject($value[0]);
             } elseif (array_key_exists(0, $value)) {
                 $value['label'] = $value[0];
             }
         }
     }
     if (count($value) == 0) {
         $value = array('label' => '', 'link' => '');
     }
     if (FabrikWorker::getMenuOrRequestVar('rowid') == 0 && FArrayHelper::getValue($value, 'link', '') === '') {
         $value['link'] = $params->get('link_default_url');
     }
     if (!$this->isEditable()) {
         $lbl = trim(FArrayHelper::getValue($value, 'label'));
         $href = trim(FArrayHelper::getValue($value, 'link'));
         $w = new FabrikWorker();
         $href = is_array($data) ? $w->parseMessageForPlaceHolder($href, $data) : $w->parseMessageForPlaceHolder($href);
         $opts['target'] = trim($params->get('link_target', ''));
         $opts['smart_link'] = $params->get('link_smart_link', false);
         $opts['rel'] = $params->get('rel', '');
         $title = $params->get('link_title', '');
         if ($title !== '') {
             $opts['title'] = strip_tags($w->parseMessageForPlaceHolder($title, $data));
         }
         return FabrikHelperHTML::a($href, $lbl, $opts);
     }
     $labelname = FabrikString::rtrimword($name, '[]') . '[label]';
     $linkname = FabrikString::rtrimword($name, '[]') . '[link]';
     $bits['name'] = $labelname;
     $bits['placeholder'] = FText::_('PLG_ELEMENT_LINK_LABEL');
     $bits['value'] = $value['label'];
     $bits['class'] .= ' fabrikSubElement';
     unset($bits['id']);
     $layout = $this->getLayout('form');
     $layoutData = new stdClass();
     $layoutData->id = $id;
     $layoutData->name = $name;
     $layoutData->linkAttributes = $bits;
     $bits['placeholder'] = FText::_('PLG_ELEMENT_LINK_URL');
     $bits['name'] = $linkname;
     $bits['value'] = FArrayHelper::getValue($value, 'link');
     if (is_a($bits['value'], 'stdClass')) {
         $bits['value'] = $bits['value']->{0};
     }
     $layoutData->labelAttributes = $bits;
     return $layout->render($layoutData);
 }
Пример #20
0
 /**
  * Display the template
  *
  * @param   sting  $tpl  template
  *
  * @return void
  */
 public function display($tpl = null)
 {
     $input = $this->app->input;
     /** @var FabrikFEModelList $model */
     $model = $this->getModel();
     $model->setId($input->getInt('listid'));
     if (!parent::access($model)) {
         exit;
     }
     $table = $model->getTable();
     $params = $model->getParams();
     $rowId = $input->getString('rowid', '', 'string');
     list($this->headings, $groupHeadings, $this->headingClass, $this->cellClass) = $this->get('Headings');
     $data = $model->render();
     $this->emptyDataMessage = $this->get('EmptyDataMsg');
     $nav = $model->getPagination();
     $form = $model->getFormModel();
     $c = 0;
     foreach ($data as $groupKey => $group) {
         foreach ($group as $i => $x) {
             $o = new stdClass();
             if (is_object($data[$groupKey])) {
                 $o->data = ArrayHelper::fromObject($data[$groupKey]);
             } else {
                 $o->data = $data[$groupKey][$i];
             }
             if (array_key_exists($groupKey, $model->groupTemplates)) {
                 $o->groupHeading = $model->groupTemplates[$groupKey] . ' ( ' . count($group) . ' )';
             }
             $o->cursor = $i + $nav->limitstart;
             $o->total = $nav->total;
             $o->id = 'list_' . $model->getRenderContext() . '_row_' . @$o->data->__pk_val;
             $o->class = 'fabrik_row oddRow' . $c;
             if (is_object($data[$groupKey])) {
                 $data[$groupKey] = $o;
             } else {
                 $data[$groupKey][$i] = $o;
             }
             $c = 1 - $c;
         }
     }
     $groups = $form->getGroupsHiarachy();
     foreach ($groups as $groupModel) {
         $elementModels = $groupModel->getPublishedElements();
         foreach ($elementModels as $elementModel) {
             $elementModel->setContext($groupModel, $form, $model);
             $elementModel->setRowClass($data);
         }
     }
     $d = array('id' => $table->id, 'listRef' => $input->get('listref'), 'rowid' => $rowId, 'model' => 'list', 'data' => $data, 'headings' => $this->headings, 'formid' => $model->getTable()->form_id, 'lastInsertedRow' => $this->session->get('lastInsertedRow', 'test'));
     $d['nav'] = get_object_vars($nav);
     $tmpl = $input->get('tmpl', $this->getTmpl());
     $d['htmlnav'] = $params->get('show-table-nav', 1) ? $nav->getListFooter($model->getId(), $tmpl) : '';
     $d['calculations'] = $model->getCalculations();
     // $$$ hugh - see if we have a message to include, set by a list plugin
     $context = 'com_' . $this->package . '.list' . $model->getRenderContext() . '.msg';
     if ($this->session->has($context)) {
         $d['msg'] = $this->session->get($context);
         $this->session->clear($context);
     }
     echo json_encode($d);
 }
Пример #21
0
 /**
  * Get html form fields for a plugin (filled with
  * current element's plugin data
  *
  * @param   string $plugin plugin name
  *
  * @return  string    html form fields
  */
 public function getPluginHTML($plugin = null)
 {
     $item = $this->getItem();
     if (is_null($plugin)) {
         $plugin = $item->plugin;
     }
     JPluginHelper::importPlugin('fabrik_cron');
     // Trim old f2 cron prefix.
     $plugin = FabrikString::ltrimiword($plugin, 'cron');
     if ($plugin == '') {
         $str = '<div class="alert">' . FText::_('COM_FABRIK_SELECT_A_PLUGIN') . '</div>';
     } else {
         $plugin = $this->pluginManager->getPlugIn($plugin, 'Cron');
         $mode = FabrikWorker::j3() ? 'nav-tabs' : '';
         $str = $plugin->onRenderAdminSettings(ArrayHelper::fromObject($item), null, $mode);
     }
     return $str;
 }
Пример #22
0
 /**
  * Set user group ids
  *
  * @param   object $me   New joomla user
  * @param   object $user Joomla user before juser plugin run
  *
  * @return  array   group ids
  */
 protected function setGroupIds($me, $user)
 {
     $formModel = $this->getModel();
     $isNew = $user->get('id') < 1;
     $params = $this->getParams();
     $this->gidfield = $this->getFieldName('juser_field_usertype');
     $defaultGroup = (int) $params->get('juser_field_default_group');
     $groupIds = (array) $this->getFieldValue('juser_field_usertype', $formModel->formData, $defaultGroup);
     // If the group ids where encrypted (e.g. user can't edit the element) they appear as an object in groupIds[0]
     if (!empty($groupIds) && is_object($groupIds[0])) {
         $groupIds = ArrayHelper::fromObject($groupIds[0]);
     }
     $groupIds = ArrayHelper::toInteger($groupIds);
     $data = array();
     if ($params->get('juser_field_usertype') != '') {
         if ($isNew) {
             //If array but empty (e.g. from an empty user_groups element)
             if (empty($groupIds)) {
                 $groupIds = (array) $defaultGroup;
             }
             $data = count($groupIds) === 1 && $groupIds[0] == 0 ? (array) $defaultGroup : $this->filterGroupIds($data, $me, $groupIds);
         } else {
             $data = $this->filterGroupIds($data, $me, $groupIds);
         }
     } else {
         // If editing an existing user and no gid field being used,  use default group id
         $data[] = $defaultGroup;
     }
     return $data;
 }
Пример #23
0
 /**
  * Get the number of times the group was repeated based on the form's current data
  *
  * @since   3.1rc1
  *
  * @return number
  */
 public function repeatCount()
 {
     $data = $this->getFormModel()->getData();
     $elementModels = $this->getPublishedElements();
     reset($elementModels);
     $tmpElement = current($elementModels);
     if (!empty($elementModels)) {
         $smallerElHTMLName = $tmpElement->getFullName(true, false);
         $d = FArrayHelper::getValue($data, $smallerElHTMLName, array());
         if (is_object($d)) {
             $d = ArrayHelper::fromObject($d);
         }
         $repeatGroup = count($d);
     } else {
         // No published elements - not sure if setting repeatGroup to 0 is right though
         $repeatGroup = 0;
     }
     return $repeatGroup;
 }
Пример #24
0
 /**
  * Perform log
  *
  * @param   string $messageType message type
  *
  * @return    bool
  */
 protected function log($messageType)
 {
     $params = $this->getParams();
     $formModel = $this->getModel();
     $input = $this->app->input;
     $db = FabrikWorker::getDBO();
     $rowId = $input->get('rowid', '', 'string');
     $loading = strstr($messageType, 'form.load');
     $http_referrer = $input->server->get('HTTP_REFERER', 'no HTTP_REFERER', 'string');
     $userId = $this->user->get('id');
     $username = $this->user->get('username');
     // Generate random filename
     if ($params->get('logs_random_filename') == 1) {
         $randomFileName = '_' . $this->generateFilename($params->get('logs_random_filename_length'));
     } else {
         $randomFileName = '';
     }
     $w = new FabrikWorker();
     $logsPath = $w->parseMessageForPlaceHolder($params->get('logs_path'));
     if (strpos($logsPath, '/') !== 0) {
         $logsPath = JPATH_ROOT . '/' . $logsPath;
     }
     $logsPath = rtrim($logsPath, '/');
     if (!JFolder::exists($logsPath)) {
         if (!JFolder::create($logsPath)) {
             return;
         }
     }
     $ext = $params->get('logs_file_format');
     $sep = $params->get('logs_separator');
     // Making complete path + filename + extension
     $w = new FabrikWorker();
     $logsFile = $logsPath . '/' . $w->parseMessageForPlaceHolder($params->get('logs_file')) . $randomFileName . '.' . $ext;
     $logsMode = $params->get('logs_append_or_overwrite');
     $date_element = $params->get('logs_date_field');
     $date_now = $params->get('logs_date_now');
     // COMPARE DATA
     $result_compare = '';
     if ($params->get('compare_data')) {
         if ($ext == 'csv') {
             $sep_compare = '';
             $sep_2compare = '/ ';
         } elseif ($ext == 'txt') {
             $sep_compare = "\n";
             $sep_2compare = "\n";
         } elseif ($ext == 'htm') {
             $sep_compare = '<br/>';
             $sep_2compare = '<br/>';
         }
         if ($loading) {
             $result_compare = FText::_('COMPARE_DATA_LOADING') . $sep_2compare;
         } else {
             $data = $this->getProcessData();
             $newData = $this->getNewData();
             if (!empty($data)) {
                 $filter = JFilterInput::getInstance();
                 $post = $filter->clean($_POST, 'array');
                 $tableModel = $formModel->getTable();
                 $origDataCount = count(array_keys(ArrayHelper::fromObject($formModel->_origData[0])));
                 if ($origDataCount > 0) {
                     $c = 0;
                     $origData = $formModel->_origData;
                     $log_elements = $params->get('logs_element_list', '');
                     if (!empty($log_elements)) {
                         $log_elements = explode(',', str_replace(' ', '', $log_elements));
                     }
                     $groups = $formModel->getGroupsHiarachy();
                     foreach ($groups as $groupModel) {
                         $group = $groupModel->getGroup();
                         $elementModels = $groupModel->getPublishedElements();
                         foreach ($elementModels as $elementModel) {
                             $element = $elementModel->getElement();
                             $fullName = $elementModel->getFullName(true, false);
                             if (empty($log_elements) || in_array($fullName, $log_elements)) {
                                 if ($newData[$c]->{$fullName} != $origData[$c]->{$fullName}) {
                                     $result_compare .= FText::_('COMPARE_DATA_CHANGE_ON') . ' ' . $element->label . ' ' . $sep_compare . FText::_('COMPARE_DATA_FROM') . ' ' . $origData[0]->{$fullName} . ' ' . $sep_compare . FText::_('COMPARE_DATA_TO') . ' ' . $newData[$c]->{$fullName} . ' ' . $sep_2compare;
                                 }
                             }
                         }
                     }
                     if (empty($result_compare)) {
                         $result_compare = FText::_('COMPARE_DATA_NO_DIFFERENCES');
                     }
                 } else {
                     $result_compare .= "New record:" . $sep_2compare;
                     foreach ($data as $key => $val) {
                         if (isset($val) && substr($key, -4, 4) != '_raw') {
                             $result_compare .= "{$key} : {$val}" . $sep_2compare;
                         }
                     }
                 }
             } else {
                 $result_compare = "No data to compare!";
             }
         }
     }
     // Defining the date to use - Not used any more as logs should really only record the current time_date
     if ($date_now != '') {
         $date = date("{$date_now}");
     } else {
         $date = date("Y-m-d H:i:s");
     }
     // Custom Message
     if ($params->get('custom_msg') != '') {
         $rep_add_edit = $messageType == 'form.add' ? FText::_('REP_ADD') : ($messageType == 'form.edit' ? FText::_('REP_EDIT') : FText::_('DETAILS'));
         $custom_msg = $params->get('custom_msg');
         $custom_msg = preg_replace('/{Add\\/Edit}/', $rep_add_edit, $custom_msg);
         $custom_msg = preg_replace('/{DATE}/', $date, $custom_msg);
         $excl_clabels = preg_replace('/([-{2}| |"][0-9a-zA-Z.:$_>]*)/', '', $custom_msg);
         $split_clabels = preg_split('/[+]{1,}/', $excl_clabels);
         $clabels = preg_replace('/[={2}]+[a-zA-Z0-9_-]*/', '', $split_clabels);
         $ctypes = preg_replace('/[a-zA-Z0-9_-]*[={2}]/', '', $split_clabels);
         $labtyp = array_combine($clabels, $ctypes);
         $w = new FabrikWorker();
         $custom_msg = $w->parseMessageForPlaceHolder($custom_msg);
         $regex = '/((?!("[^"]*))([ |\\w|+|.])+(?=[^"]*"\\b)|(?!\\b"[^"]*)( +)+(?=([^"]*)$)|(?=\\b"[^"]*)( +)+(?=[^"]*"\\b))/';
         $excl_cdata = preg_replace($regex, '', $custom_msg);
         $cdata = preg_split('/["]{1,}/', $excl_cdata);
         // Labels for CSV & for DB
         $clabels_csv_imp = implode("\",\"", $clabels);
         $clabels_csv_p1 = preg_replace('/^(",)/', '', $clabels_csv_imp);
         $clabels_csv = '';
         $clabels_csv .= preg_replace('/(,")$/', '', $clabels_csv_p1);
         if ($params->get('compare_data') == 1) {
             $clabels_csv .= ', "' . FText::_('PLG_FORM_LOG_COMPARE_DATA_LABEL_CSV') . '"';
         }
         $clabels_createdb_imp = '';
         foreach ($labtyp as $klb => $vlb) {
             $klb = $db->qn($klb);
             if ($vlb == 'varchar') {
                 $clabels_createdb_imp .= $klb . ' ' . $vlb . '(255) NOT NULL, ';
             } elseif ($vlb == 'int') {
                 $clabels_createdb_imp .= $klb . ' ' . $vlb . '(11) NOT NULL, ';
             } elseif ($vlb == 'datetime') {
                 $clabels_createdb_imp .= $klb . ' ' . $vlb . ' NOT NULL, ';
             }
         }
         $clabels_createdb = JString::substr_replace($clabels_createdb_imp, '', -2);
         if ($params->get('compare_data') == 1) {
             $clabels_createdb .= ', ' . $db->qn(FText::_('COMPARE_DATA_LABEL_DB')) . ' text NOT NULL';
         }
         // @todo - what if we use different db driver which doesn't name quote with `??
         $clabels_db_imp = implode("`,`", $clabels);
         $clabels_db_p1 = preg_replace('/^(`,)/', '', $clabels_db_imp);
         $clabels_db = preg_replace('/(,`)$/', '', $clabels_db_p1);
         if ($params->get('compare_data') == 1) {
             $clabels_db .= ', ' . $db->qn(FText::_('PLG_FORM_LOG_COMPARE_DATA_LABEL_DB'));
         }
         // Data for CSV & for DB
         $cdata_csv_imp = implode("\",\"", $cdata);
         $cdata_csv_p1 = preg_replace('/^(",)/', '', $cdata_csv_imp);
         $cdata_csv = preg_replace('/(,")$/', '', $cdata_csv_p1);
         $cdata_csv = preg_replace('/={1,}",/', '', $cdata_csv);
         $cdata_csv = preg_replace('/""/', '"', $cdata_csv);
         if ($params->get('compare_data') == 1) {
             $cdata_csv .= ', "' . $result_compare . '"';
         }
         $cdata_db_imp = implode("','", $cdata);
         $cdata_db_p1 = preg_replace("/^(',)/", '', $cdata_db_imp);
         $cdata_db = preg_replace("/(,')\$/", '', $cdata_db_p1);
         $cdata_db = preg_replace("/={1,}',/", '', $cdata_db);
         $cdata_db = preg_replace("/''/", "'", $cdata_db);
         if ($params->get('compare_data') == 1 && !$loading) {
             $result_compare = preg_replace('/<br\\/>/', '- ', $result_compare);
             $result_compare = preg_replace('/\\n/', '- ', $result_compare);
             $cdata_db .= ", '" . $result_compare . "'";
         }
         $custom_msg = preg_replace('/([++][0-9a-zA-Z.:_]*)/', '', $custom_msg);
         $custom_msg = preg_replace('/^[ ]/', '', $custom_msg);
         $custom_msg = preg_replace('/  /', ' ', $custom_msg);
         $custom_msg = preg_replace('/"/', '', $custom_msg);
         if ($params->get('compare_data') == 1 && !$loading) {
             $custom_msg .= '<br />' . $result_compare;
         }
     } else {
         $clabelsCreateDb = array();
         $clabelsDb = array();
         $cdataDb = array();
         $clabelsCreateDb[] = $db->qn('date') . " datetime NOT NULL";
         $clabelsDb[] = $db->qn('date');
         $cdataDb[] = "NOW()";
         $clabelsCreateDb[] = $db->qn('ip') . " varchar(32) NOT NULL";
         $clabelsDb[] = $db->qn('ip');
         $cdataDb[] = $params->get('logs_record_ip') == '1' ? $db->q(FabrikString::filteredIp()) : $db->q('');
         $clabelsCreateDb[] = $db->qn('referer') . " varchar(255) NOT NULL";
         $clabelsDb[] = $db->qn('referer');
         $cdataDb[] = $params->get('logs_record_referer') == '1' ? $db->q($http_referrer) : $db->q('');
         $clabelsCreateDb[] = $db->qn('user_agent') . " varchar(255) NOT NULL";
         $clabelsDb[] = $db->qn('user_agent');
         $cdataDb[] = $params->get('logs_record_useragent') == '1' ? $db->q($input->server->getString('HTTP_USER_AGENT')) : $db->q('');
         $clabelsCreateDb[] = $db->qn('data_comparison') . " TEXT NOT NULL";
         $clabelsDb[] = $db->qn('data_comparison');
         $cdataDb[] = $params->get('compare_data') == '1' ? $db->q($result_compare) : $db->q('');
         $clabelsCreateDb[] = $db->qn('rowid') . " INT(11) NOT NULL";
         $clabelsDb[] = $db->qn('rowid');
         $cdataDb[] = $db->q($rowId);
         $clabelsCreateDb[] = $db->qn('userid') . " INT(11) NOT NULL";
         $clabelsDb[] = $db->qn('userid');
         $cdataDb[] = $db->q((int) $userId);
         $clabelsCreateDb[] = $db->qn('tableid') . " INT(11) NOT NULL";
         $clabelsDb[] = $db->qn('tableid');
         $cdataDb[] = $db->q($formModel->getListModel()->getId());
         $clabelsCreateDb[] = $db->qn('formid') . " INT(11) NOT NULL";
         $clabelsDb[] = $db->qn('formid');
         $cdataDb[] = $db->q($formModel->getId());
         $clabels_createdb = implode(", ", $clabelsCreateDb);
         $clabels_db = implode(", ", $clabelsDb);
         $cdata_db = implode(", ", $cdataDb);
     }
     /* For CSV files
      * If 'Append' method is used, you don't want to repeat the labels (Date, IP, ...)
      * each time you add a line in the file */
     $labels = !JFile::exists($logsFile) || $logsMode == 'w' ? 1 : 0;
     $buffer = $logsMode == 'a' && JFile::exists($logsFile) ? file_get_contents($logsFile) : '';
     $send_email = $params->get('log_send_email') == '1';
     $make_file = $params->get('make_file') == '1';
     if ($send_email && !$make_file) {
         $ext = 'txt';
     }
     $email_msg = '';
     // @TODO redo all this with JFile API and only writing a string once - needless overhead doing fwrite all the time
     if ($make_file || $send_email) {
         // Opening or creating the file
         if ($params->get('custom_msg') != '') {
             if ($send_email) {
                 $email_msg = $custom_msg;
             }
             if ($make_file) {
                 $custMsg = $buffer;
                 if ($ext != 'csv') {
                     $thisMsg = $buffer . $custom_msg . "\n" . $sep . "\n";
                     JFile::write($logsFile, $thisMsg);
                 } else {
                     // Making the CSV file
                     // If the file already exists, do not add the 'label line'
                     if ($labels == 1) {
                         $custMsg .= $clabels_csv;
                     }
                     // Inserting data in CSV with actual line break as row separator
                     $custMsg .= "\n" . $cdata_csv;
                     JFile::write($logsFile, $custMsg);
                 }
             }
         } else {
             // Making HTM File
             if ($ext == 'htm') {
                 $htmlMsg = "<b>Date:</b> " . $date . "<br/>";
                 if ($params->get('logs_record_ip') == 1) {
                     $htmlMsg .= "<b>IP Address:</b> " . FabrikString::filteredIp() . "<br/>";
                 }
                 if ($params->get('logs_record_referer') == 1) {
                     $htmlMsg .= "<b>Referer:</b> " . $http_referrer . "<br/>";
                 }
                 if ($params->get('logs_record_useragent') == 1) {
                     $htmlMsg .= "<b>UserAgent: </b>" . $input->server->getString('HTTP_USER_AGENT') . "<br/>";
                 }
                 $htmlMsg .= $result_compare . $sep . "<br/>";
                 if ($send_email) {
                     $email_msg = $htmlMsg;
                 }
                 if ($make_file) {
                     $htmlMsg = $buffer . $htmlMsg;
                     $res = JFile::write($logsFile, $htmlMsg);
                     if (!$res) {
                         $this->app->enqueueMessage("error writing html to log file: " . $logsFile, 'notice');
                     }
                 }
             } elseif ($ext == 'txt') {
                 $txtMsg = "Date: " . $date . "\n";
                 $txtMsg .= "Form ID: " . $formModel->getId() . "\n";
                 $txtMsg .= "Table ID: " . $formModel->getListModel()->getId() . "\n";
                 $txtMsg .= "Row ID: " . $rowId . "\n";
                 $txtMsg .= "User ID: {$userId} ({$username})\n";
                 if ($params->get('logs_record_ip') == 1) {
                     $txtMsg .= "IP Address: " . FabrikString::filteredIp() . "\n";
                 }
                 if ($params->get('logs_record_referer') == 1) {
                     $txtMsg .= "Referer: " . $http_referrer . "\n";
                 }
                 if ($params->get('logs_record_useragent') == 1) {
                     $txtMsg .= "UserAgent: " . $input->server->getString('HTTP_USER_AGENT') . "\n";
                 }
                 $txtMsg .= $result_compare . $sep . "\n";
                 if ($send_email) {
                     $email_msg = $txtMsg;
                 }
                 if ($make_file) {
                     $txtMsg = $buffer . $txtMsg;
                     JFile::write($logsFile, $txtMsg);
                 }
             } elseif ($ext == 'csv') {
                 // Making the CSV file
                 $csvMsg = array();
                 // If the file already exists, do not add the 'label line'
                 if ($labels == 1) {
                     $csvMsg[] = "Date";
                     if ($params->get('logs_record_ip') == 1) {
                         // Putting some "" around the label to avoid two different fields
                         $csvMsg[] = "\"IP Address\"";
                     }
                     if ($params->get('logs_record_referer') == 1) {
                         $csvMsg[] = "Referer";
                     }
                     if ($params->get('logs_record_useragent') == 1) {
                         $csvMsg[] = "UserAgent";
                     }
                     if ($params->get('compare_data') == 1) {
                         $csvMsg[] = "\"" . FText::_('COMPARE_DATA_LABEL_CSV') . "\"";
                     }
                 }
                 // Inserting data in CSV with actual line break as row separator
                 $csvMsg[] = "\n\"" . $date . "\"";
                 if ($params->get('logs_record_ip') == 1) {
                     $csvMsg[] = "\"" . FabrikString::filteredIp() . "\"";
                 }
                 if ($params->get('logs_record_referer') == 1) {
                     $csvMsg[] = "\"" . $http_referrer . "\"";
                 }
                 if ($params->get('logs_record_useragent') == 1) {
                     $csvMsg[] = "\"" . $input->server->getString('HTTP_USER_AGENT') . "\"";
                 }
                 if ($params->get('compare_data') == 1) {
                     $csvMsg[] = "\"" . $result_compare . "\"";
                 }
                 $csvMsg = implode(",", $csvMsg);
                 if ($send_email) {
                     $email_msg = $csvMsg;
                 }
                 if ($make_file) {
                     if ($buffer !== '') {
                         $csvMsg = $buffer . $csvMsg;
                     }
                     JFile::write($logsFile, $csvMsg);
                 }
             }
         }
     }
     if ($params->get('logs_record_in_db') == 1) {
         // In which table?
         if ($params->get('record_in') == '') {
             $rdb = '#__fabrik_log';
         } else {
             $db_suff = $params->get('record_in');
             $form = $formModel->getForm();
             $fid = $form->id;
             $db->setQuery("SELECT " . $db->qn('db_table_name') . " FROM " . $db->qn('#__fabrik_lists') . " WHERE " . $db->qn('form_id') . " = " . (int) $fid);
             $tname = $db->loadResult();
             $rdb = $db->qn($tname . $db_suff);
         }
         // Making the message to record
         if ($params->get('custom_msg') != '') {
             $message = preg_replace('/<br\\/>/', ' ', $custom_msg);
         } else {
             $message = $this->makeStandardMessage($result_compare);
         }
         /* $$$ hugh - FIXME - not sure about the option driven $create_custom_table stuff, as this won't work
          * if they add an option to an existing log table.  We should probably just create all the optional columns
          * regardless.
          */
         if ($params->get('record_in') == '') {
             $in_db = "INSERT INTO {$rdb} (" . $db->qn('referring_url') . ", " . $db->qn('message_type') . ", " . $db->qn('message') . ") VALUES (" . $db->q($http_referrer) . ", " . $db->q($messageType) . ", " . $db->q($message) . ");";
             $db->setQuery($in_db);
             $db->execute();
         } else {
             $create_custom_table = "CREATE TABLE IF NOT EXISTS {$rdb} (" . $db->qn('id') . " int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, {$clabels_createdb});";
             $db->setQuery($create_custom_table);
             $db->execute();
             $in_db = "INSERT INTO {$rdb} ({$clabels_db}) VALUES ({$cdata_db});";
             $db->setQuery($in_db);
             if (!$db->execute()) {
                 /* $$$ changed to always use db fields even if not selected
                  * so logs already created may need optional fields added.
                  * try adding every field we should have, don't care if query fails.
                  */
                 foreach ($clabelsCreateDb as $insert) {
                     $db->setQuery("ALTER TABLE ADD {$insert} AFTER `id`");
                     $db->execute();
                 }
                 // ... and try the insert query again
                 $db->setQuery($in_db);
                 $db->execute();
             }
         }
     }
     if ($send_email) {
         jimport('joomla.mail.helper');
         $emailFrom = $this->config->get('mailfrom');
         $emailTo = explode(',', $w->parseMessageForPlaceholder($params->get('log_send_email_to', '')));
         $subject = strip_tags($w->parseMessageForPlaceholder($params->get('log_send_email_subject', 'log event')));
         foreach ($emailTo as $email) {
             $email = trim($email);
             if (empty($email)) {
                 continue;
             }
             if (FabrikWorker::isEmail($email)) {
                 $mail = JFactory::getMailer();
                 $res = $mail->sendMail($emailFrom, $emailFrom, $email, $subject, $email_msg, true);
             } else {
                 $app->enqueueMessage(JText::sprintf('DID_NOT_SEND_EMAIL_INVALID_ADDRESS', $email));
             }
         }
     }
     return true;
 }
Пример #25
0
 /**
  * Set type title.
  *
  * <code>
  * $params = array(
  *     "rewards_enabled" = Prism\Constants::ENABLED
  * );
  *
  * $type    = new Crowdfunding\Type(\JFactory::getDbo());
  * $type->load($typeId);
  *
  * $type->setParams($params);
  * $type->store();
  * </code>
  *
  * @param mixed $params
  *
  * @return self
  */
 public function setParams($params)
 {
     if (is_string($params)) {
         $this->params = (array) json_decode($params, true);
     } elseif (is_object($params)) {
         $this->params = ArrayHelper::fromObject($params);
     } elseif (is_array($params)) {
         $this->params = $params;
     } else {
         $this->params = array();
     }
     return $this;
 }
Пример #26
0
 /**
  * Send the remind username email
  *
  * @param   array  $data  Array with the data received from the form
  *
  * @return  boolean
  *
  * @since   1.6
  */
 public function processRemindRequest($data)
 {
     // Get the form.
     $form = $this->getForm();
     $data['email'] = JStringPunycode::emailToPunycode($data['email']);
     // Check for an error.
     if (empty($form)) {
         return false;
     }
     // Validate the data.
     $data = $this->validate($form, $data);
     // Check for an error.
     if ($data instanceof Exception) {
         return false;
     }
     // Check the validation results.
     if ($data === false) {
         // Get the validation messages from the form.
         foreach ($form->getErrors() as $formError) {
             $this->setError($formError->getMessage());
         }
         return false;
     }
     // Find the user id for the given email address.
     $db = $this->getDbo();
     $query = $db->getQuery(true)->select('*')->from($db->quoteName('#__users'))->where($db->quoteName('email') . ' = ' . $db->quote($data['email']));
     // Get the user id.
     $db->setQuery($query);
     try {
         $user = $db->loadObject();
     } catch (RuntimeException $e) {
         $this->setError(JText::sprintf('COM_USERS_DATABASE_ERROR', $e->getMessage()), 500);
         return false;
     }
     // Check for a user.
     if (empty($user)) {
         $this->setError(JText::_('COM_USERS_USER_NOT_FOUND'));
         return false;
     }
     // Make sure the user isn't blocked.
     if ($user->block) {
         $this->setError(JText::_('COM_USERS_USER_BLOCKED'));
         return false;
     }
     $config = JFactory::getConfig();
     // Assemble the login link.
     $itemid = UsersHelperRoute::getLoginRoute();
     $itemid = $itemid !== null ? '&Itemid=' . $itemid : '';
     $link = 'index.php?option=com_users&view=login' . $itemid;
     $mode = $config->get('force_ssl', 0) == 2 ? 1 : -1;
     // Put together the email template data.
     $data = ArrayHelper::fromObject($user);
     $data['fromname'] = $config->get('fromname');
     $data['mailfrom'] = $config->get('mailfrom');
     $data['sitename'] = $config->get('sitename');
     $data['link_text'] = JRoute::_($link, false, $mode);
     $data['link_html'] = JRoute::_($link, true, $mode);
     $subject = JText::sprintf('COM_USERS_EMAIL_USERNAME_REMINDER_SUBJECT', $data['sitename']);
     $body = JText::sprintf('COM_USERS_EMAIL_USERNAME_REMINDER_BODY', $data['sitename'], $data['username'], $data['link_text']);
     // Send the password reset request email.
     $return = JFactory::getMailer()->sendMail($data['mailfrom'], $data['fromname'], $user->email, $subject, $body);
     // Check for an error.
     if ($return !== true) {
         $this->setError(JText::_('COM_USERS_MAIL_FAILED'), 500);
         return false;
     }
     return true;
 }
Пример #27
0
 /**
  * Write the current batch section of the CSV file
  *
  * @param   int  $total       Total # of records
  * @param   bool $canDownload Can we also download the file (at end of export)
  *
  * @return  null
  */
 public function writeFile($total, $canDownload = false)
 {
     $params = $this->model->getParams();
     $input = $this->app->input;
     // F3 turn off error reporting as this is an ajax call
     error_reporting(0);
     jimport('joomla.filesystem.file');
     $start = $input->getInt('start', 0);
     $filePath = $this->getFilePath();
     $str = '';
     if (JFile::exists($filePath)) {
         if ($start === 0) {
             JFile::delete($filePath);
         } else {
             $str = file_get_contents($filePath);
         }
     } else {
         // Fabrik3 odd cant pass 2nd param by reference if we try to write '' so assign it to $tmp first
         $tmp = '';
         $ok = JFile::write($filePath, $tmp);
         if (!$ok) {
             $this->reportWriteError($filePath);
             exit;
         }
         // with UTF8 Excel needs BOM
         $str = $input->get('excel') == 1 && $this->getEncoding() == 'UTF-8' ? "" : '';
     }
     $table = $this->model->getTable();
     $this->model->render();
     $this->removePkVal();
     $this->outPutFormat = $input->get('excel') == 1 ? 'excel' : 'csv';
     $config = JComponentHelper::getParams('com_fabrik');
     $this->delimiter = $this->outPutFormat == 'excel' ? COM_FABRIK_EXCEL_CSV_DELIMITER : COM_FABRIK_CSV_DELIMITER;
     $this->delimiter = $config->get('csv_delimiter', $this->delimiter);
     $local_delimiter = $this->model->getParams()->get('csv_local_delimiter');
     if ($local_delimiter != '') {
         $this->delimiter = $local_delimiter;
     }
     if ($this->delimiter === '\\t') {
         $this->delimiter = "\t";
     }
     $end_of_line = $this->model->getParams()->get('csv_end_of_line');
     if ($end_of_line == 'r') {
         $end_of_line = "\r";
     } else {
         $end_of_line = "\n";
     }
     if ($start === 0) {
         $headings = $this->getHeadings();
         if (empty($headings)) {
             $url = $input->server->get('HTTP_REFERER', '');
             $this->app->enqueueMessage(FText::_('No data to export'));
             $this->app->redirect($url);
             return;
         }
         $str .= implode($headings, $this->delimiter) . $end_of_line;
     }
     $incRaw = $input->get('incraw', true);
     $incData = $input->get('inctabledata', true);
     $data = $this->model->getData();
     $exportFormat = $this->model->getParams()->get('csvfullname');
     $shortKey = FabrikString::shortColName($table->db_primary_key);
     $a = array();
     foreach ($data as $group) {
         foreach ($group as $row) {
             $a = ArrayHelper::fromObject($row);
             if ($exportFormat == 1) {
                 unset($a[$shortKey]);
             }
             if (!$incRaw) {
                 foreach ($a as $key => $val) {
                     if (substr($key, JString::strlen($key) - 4, JString::strlen($key)) == '_raw') {
                         unset($a[$key]);
                     }
                 }
             }
             if (!$incData) {
                 foreach ($a as $key => $val) {
                     if (substr($key, JString::strlen($key) - 4, JString::strlen($key)) != '_raw') {
                         unset($a[$key]);
                     }
                 }
             }
             if ($incData && $incRaw) {
                 foreach ($a as $key => $val) {
                     // Remove Un-needed repeat join element values.
                     if (array_key_exists($key . '___params', $a)) {
                         unset($a[$key . '___params']);
                     }
                     if (array_key_exists($key . '_id', $a)) {
                         unset($a[$key . '_id']);
                     }
                 }
             }
             if ($input->get('inccalcs') == 1) {
                 array_unshift($a, ' ');
             }
             $this->carriageReturnFix($a);
             if ($params->get('csv_format_json', '1') === '1') {
                 array_walk($a, array($this, 'implodeJSON'), $end_of_line);
             }
             $str .= implode($this->delimiter, array_map(array($this, 'quote'), array_values($a)));
             $str .= $end_of_line;
         }
     }
     $res = new stdClass();
     $res->total = $total;
     $res->count = $start + $this->getStep();
     $res->file = basename($filePath);
     $res->limitStart = $start;
     $res->limitLength = $this->getStep();
     if ($res->count >= $res->total) {
         $this->addCalculations($a, $str);
     }
     error_reporting(0);
     $ok = JFile::write($filePath, $str);
     if (!$ok) {
         $this->reportWriteError($filePath);
         exit;
     } else {
         if (!$canDownload) {
             echo json_encode($res);
         }
     }
 }
Пример #28
0
 /**
  * Display session information.
  *
  * Called recursively.
  *
  * @param   string   $key      A session key.
  * @param   mixed    $session  The session array, initially null.
  * @param   integer  $id       Used to identify the DIV for the JavaScript toggling code.
  *
  * @return  string
  *
  * @since   2.5
  */
 protected function displaySession($key = '', $session = null, $id = 0)
 {
     if (!$session) {
         $session = JFactory::getSession()->getData();
     }
     $html = array();
     static $id;
     if (!is_array($session)) {
         $html[] = $key . '<pre>' . $this->prettyPrintJSON($session) . '</pre>' . PHP_EOL;
     } else {
         foreach ($session as $sKey => $entries) {
             $display = true;
             if (is_array($entries) && $entries) {
                 $display = false;
             }
             if (is_object($entries)) {
                 $o = ArrayHelper::fromObject($entries);
                 if ($o) {
                     $entries = $o;
                     $display = false;
                 }
             }
             if (!$display) {
                 $js = "toggleContainer('dbg_container_session" . $id . '_' . $sKey . "');";
                 $html[] = '<div class="dbg-header" onclick="' . $js . '"><a href="javascript:void(0);"><h3>' . $sKey . '</h3></a></div>';
                 // @todo set with js.. ?
                 $style = ' style="display: none;"';
                 $html[] = '<div ' . $style . ' class="dbg-container" id="dbg_container_session' . $id . '_' . $sKey . '">';
                 $id++;
                 // Recurse...
                 $this->displaySession($sKey, $entries, $id);
                 $html[] = '</div>';
                 continue;
             }
             if (is_array($entries)) {
                 $entries = implode($entries);
             }
             if (is_string($entries)) {
                 $html[] = $sKey . '<pre>' . $this->prettyPrintJSON($entries) . '</pre>' . PHP_EOL;
             }
         }
     }
     return implode('', $html);
 }
Пример #29
0
 /**
  * Load Fabrik's framework (js and base css file)
  *
  * @return  array  Framework js files
  */
 public static function framework()
 {
     if (!self::$framework) {
         $app = JFactory::getApplication();
         $version = new JVersion();
         FabrikHelperHTML::modalJLayouts();
         $liveSiteSrc = array();
         $liveSiteReq = array();
         $fbConfig = JComponentHelper::getParams('com_fabrik');
         // Only use template test for testing in 2.5 with my temp J bootstrap template.
         $bootstrapped = in_array($app->getTemplate(), array('bootstrap', 'fabrik4')) || $version->RELEASE > 2.5;
         //$ext = self::isDebug() ? '.js' : '-min.js';
         $mediaFolder = self::getMediaFolder();
         $src = array();
         JHtml::_('behavior.framework', true);
         // Ensure bootstrap js is loaded - as J template may not load it.
         if ($version->RELEASE > 2.5) {
             JHtml::_('bootstrap.framework');
             self::loadBootstrapCSS();
             JHtml::_('script', $mediaFolder . '/lib/jquery-ui/jquery-ui.min.js');
         }
         // Require js test - list with no cal loading ajax form with cal
         JHTML::_('behavior.calendar');
         $liveSiteReq['Chosen'] = $mediaFolder . '/chosen-loader';
         $liveSiteReq['Fabrik'] = $mediaFolder . '/fabrik';
         if ($bootstrapped) {
             $liveSiteReq['FloatingTips'] = $mediaFolder . '/tipsBootStrapMock';
         } else {
             $liveSiteReq['FloatingTips'] = $mediaFolder . '/tips';
         }
         if ($fbConfig->get('advanced_behavior', '0') == '1') {
             $chosenOptions = $fbConfig->get('advanced_behavior_options', '{}');
             $chosenOptions = empty($chosenOptions) ? new stdClass() : ArrayHelper::fromObject(json_decode($chosenOptions));
             JHtml::_('stylesheet', 'jui/chosen.css', false, true);
             JHtml::_('script', 'jui/chosen.jquery.min.js', false, true, false, false, self::isDebug());
             JHtml::_('script', 'jui/ajax-chosen.min', false, true, false, false, self::isDebug());
         }
         if (self::inAjaxLoadedPage() && !$bootstrapped) {
             // $$$ rob 06/02/2012 recall ant so that Color.detach is available (needed for opening a window from within a window)
             JHtml::_('script', 'media/com_fabrik/js/lib/art.js');
         }
         if ($fbConfig->get('advanced_behavior', '0') == '1') {
             $liveSiteSrc[] = "var chosenInterval = window.setInterval(function () {\r\n\t\t\t\t\t\tif (Fabrik.buildChosen) {\r\n\t\t\t\t\t\t\twindow.clearInterval(chosenInterval);\r\n\t                        Fabrik.buildChosen('select.advancedSelect', " . json_encode($chosenOptions) . ");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}, 100);";
         }
         if (!self::inAjaxLoadedPage()) {
             // Require.js now added in fabrik system plugin onAfterRender()
             JText::script('COM_FABRIK_LOADING');
             $src['Window'] = $mediaFolder . '/window.js';
             self::styleSheet(COM_FABRIK_LIVESITE . 'media/com_fabrik/css/fabrik.css');
             $liveSiteSrc[] = "\tFabrik.liveSite = '" . COM_FABRIK_LIVESITE . "';";
             $liveSiteSrc[] = "\tFabrik.package = '" . $app->getUserState('com_fabrik.package', 'fabrik') . "';";
             $liveSiteSrc[] = "\tFabrik.debug = " . (self::isDebug() ? 'true;' : 'false;');
             // need to put jLayouts in session data, and add it in the system plugin buildjs(), so just add %%jLayouts%% placeholder
             //$liveSiteSrc[] = "\tFabrik.jLayouts = " . json_encode(ArrayHelper::toObject(self::$jLayoutsJs)) . ";";
             $liveSiteSrc[] = "\tFabrik.jLayouts = %%jLayouts%%;\n";
             if ($bootstrapped) {
                 $liveSiteSrc[] = "\tFabrik.bootstrapped = true;";
             } else {
                 $liveSiteSrc[] = "\tFabrik.iconGen = new IconGenerator({scale: 0.5});";
                 $liveSiteSrc[] = "\tFabrik.bootstrapped = false;";
             }
             $liveSiteSrc[] = self::tipInt();
             $liveSiteSrc = implode("\n", $liveSiteSrc);
         } else {
             if ($bootstrapped) {
                 $liveSiteSrc[] = "\tFabrik.bootstrapped = true;";
             } else {
                 $liveSiteSrc[] = "\tFabrik.iconGen = new IconGenerator({scale: 0.5});";
                 $liveSiteSrc[] = "\tFabrik.bootstrapped = false;";
             }
             $liveSiteSrc[] = "\tif (!Fabrik.jLayouts) {\r\n\t\t\t\tFabrik.jLayouts = {};\r\n\t\t\t\t}\r\n\t\t\t\tFabrik.jLayouts = jQuery.extend(Fabrik.jLayouts, %%jLayouts%%);";
         }
         self::script($liveSiteReq, $liveSiteSrc, '-min.js');
         self::$framework = $src;
     }
     self::addToSessionJLayouts();
     return self::$framework;
 }
Пример #30
0
 private function getHeadCache()
 {
     $session = JFactory::getSession();
     $doc = JFactory::getDocument();
     $app = JFactory::getApplication();
     $uri = parse_url($app->input->server->get('HTTP_REFERER', '', 'string'));
     $key = $uri['path'];
     $qs = FArrayHelper::getValue($uri, 'query', '');
     if (!empty($qs)) {
         $key .= '?' . $qs;
     }
     $key = md5($key);
     $scripts = $this->excludeJsFiles;
     if (!empty($key)) {
         $key = 'fabrik.js.head.cache.' . $key;
         $cachedScripts = $session->get($key, '');
         if (!empty($cachedScripts)) {
             $scripts = json_decode($cachedScripts);
             $scripts = ArrayHelper::fromObject($scripts);
             $scripts = array_keys($scripts);
         }
     }
     return $scripts;
 }