/** * validate the elements data against the rule * @param string data to check * @param object element Model * @param int plugin sequence ref * @return bol true if validation passes, false if fails */ function validate($data, &$elementModel, $c) { //could be a dropdown with multivalues if (is_array($data)) { $data = implode('', $data); } $params = $this->getParams(); $element = $elementModel->getElement(); $listModel = $elementModel->getlistModel(); $table = $listModel->getTable(); $db = $listModel->getDb(); $lookuptable = $db->NameQuote($table->db_table_name); $data = $db->Quote($data); $query = $db->getQuery(true); $cond = $params->get('isuniquevalue-caseinsensitive') == 1 ? 'LIKE' : '='; $query->select('COUNT(*)')->from($lookuptable)->where($element->name . ' ' . $cond . ' ' . $data); // $$$ hugh - need to check to see if we're editing a record, otherwise // will fail 'cos it finds the original record (assuming this element hasn't changed) // @TODO - is there a better way getting the rowid? What if this is form a joined table? // $rowid = JRequest::getVar('rowid'); // Have to do it by grabbing PK from request, 'cos rowid isn't set on AJAX validation $pk = FabrikString::safeColNameToArrayKey($table->db_primary_key); $rowid = JRequest::getVar($pk, ''); if (!empty($rowid)) { $query->where($table->db_primary_key . ' != ' . $db->Quote($rowid)); } $db->setQuery($query); $c = $db->loadResult(); return $c == 0 ? true : false; }
/** * return the javascript to create an instance of the class defined in formJavascriptClass * @param object parameters * @param list table model * @param array [0] => string table's form id to contain plugin * @return bool */ function onLoadJavascriptInstance($params, $model, $args) { parent::onLoadJavascriptInstance($params, $model, $args); FabrikHelperHTML::script('media/com_fabrik/js/element.js'); $listModel = JModel::getInstance('list', 'FabrikFEModel'); $listModel->setId(JRequest::getVar('listid')); $elements = $model->getElements('safecolname'); $pels = $params->get('inline_editable_elements'); $use = json_decode($pels); if (!is_object($use)) { $aEls = trim($pels) == '' ? array() : explode(",", $pels); $use = new stdClass(); foreach ($aEls as $e) { $use->{$e} = array($e); } } $els = array(); $srcs = array(); $test = (array) $use; if (!empty($test)) { foreach ($use as $key => $fields) { $trigger = $elements[$key]; $els[$key] = new stdClass(); $els[$key]->elid = $trigger->_id; $els[$key]->plugins = array(); foreach ($fields as $field) { $val = $elements[$field]; //load in all element js classes if (is_object($val)) { $val->formJavascriptClass($srcs); $els[$key]->plugins[$field] = $val->getElement()->id; } } } } else { foreach ($elements as $key => $val) { $key = FabrikString::safeColNameToArrayKey($key); $els[$key] = new stdClass(); $els[$key]->elid = $val->_id; $els[$key]->plugins = array(); $els[$key]->plugins[$key] = $val->getElement()->id; //load in all element js classes $val->formJavascriptClass($srcs); } } FabrikHelperHTML::script($srcs); $opts = $this->getElementJSOptions($model); $opts->elements = $els; $opts->formid = $model->getFormModel()->getId(); $opts->focusClass = 'focusClass'; $opts->editEvent = $params->get('inline_edit_event', 'dblclick'); $opts->tabSave = $params->get('inline_tab_save', false); $opts->showCancel = $params->get('inline_show_cancel', true); $opts->showSave = (bool) $params->get('inline_show_save', true); $opts->loadFirst = (bool) $params->get('inline_load_first', false); $opts = json_encode($opts); $formid = 'list_' + $model->getFormModel()->getForm()->id; $this->jsInstance = "new FbListInlineEdit({$opts})"; return true; }
/** * return the javascript to create an instance of the class defined in formJavascriptClass * @param object parameters * @param object table model * @param array [0] => string table's form id to contain plugin * @return bool */ function loadJavascriptInstance($params, $model, $args) { if (!$this->canUse()) { return; } $form_id = $args[0]; FabrikHelperHTML::script('element.js', 'media/com_fabrik/js/'); $orderEl = $model->getForm()->getElement($params->get('order_element'), true); $opts = new stdClass(); $opts->enabled = count($model->orderEls) === 1 && FabrikString::safeColNameToArrayKey($model->orderEls[0]) == FabrikString::safeColNameToArrayKey($orderEl->getOrderByName()) ? true : false; $opts->liveSite = COM_FABRIK_LIVESITE; $opts->tableid = $model->_id; $opts->orderElementId = $params->get('order_element'); $opts->handle = $params->get('order_element_as_handle', 1) == 1 ? '.fabrik_row___' . $orderEl->getOrderByName() : false; $opts->direction = $opts->enabled ? $model->orderDirs[0] : ''; $opts->transition = ''; $opts->duration = ''; $opts->constrain = ''; $opts->clone = ''; $opts->revert = ''; $opts->container = 'table_' . $model->getTable()->id; $opts = json_encode($opts); $lang = $this->_getLang(); $lang = json_encode($lang); $this->jsInstance = "new FbTableOrder('{$form_id}', {$opts}, {$lang})"; return true; }
/** * Return the javascript to create an instance of the class defined in formJavascriptClass * * @param array $args Array [0] => string table's form id to contain plugin * * @return bool */ public function onLoadJavascriptInstance($args) { if (!$this->canUse()) { return; } /** @var FabrikFEModelList $model */ $model = $this->getModel(); $params = $this->getParams(); $orderEl = $model->getFormModel()->getElement($params->get('order_element'), true); $opts = $this->getElementJSOptions(); $orderElName = FabrikString::safeColNameToArrayKey(FArrayHelper::getValue($model->orderEls, 0, '')); $opts->enabled = $orderElName == FabrikString::safeColNameToArrayKey($orderEl->getOrderByName()) ? true : false; $opts->listid = $model->getId(); $opts->orderElementId = $params->get('order_element'); $opts->handle = $params->get('order_element_as_handle', 1) == 1 ? '.' . $orderEl->getOrderByName() : false; $opts->direction = $opts->enabled ? $model->orderDirs[0] : ''; $opts->transition = ''; $opts->duration = ''; $opts->constrain = ''; $opts->clone = ''; $opts->revert = ''; $opts = json_encode($opts); $this->jsInstance = "new FbListOrder({$opts})"; return true; }
/** * Tagify a string * * @param string $data Tagify * * @return string Tagified string */ protected function tagify($data) { $name = $this->getFullName(true, false); $params = $this->getParams(); $listModel = $this->getlistModel(); $filters = $listModel->getFilterArray(); $fkeys = JArrayHelper::getValue($filters, 'key', array()); $data = explode(",", strip_tags($data)); $tags = array(); $url = $params->get('textarea_tagifyurl'); if ($url == '') { $url = $_SERVER['REQUEST_URI']; $bits = explode('?', $url); $root = JArrayHelper::getValue($bits, 0, '', 'string'); $bits = JArrayHelper::getValue($bits, 1, '', 'string'); $bits = explode("&", $bits); $fullName = $this->getFullName(true, false); for ($b = count($bits) - 1; $b >= 0; $b--) { $parts = explode("=", $bits[$b]); if (count($parts) > 1) { $key = FabrikString::ltrimword(FabrikString::safeColNameToArrayKey($parts[0]), '&'); if ($key == $fullName) { unset($bits[$b]); } if ($key == $fullName . '[value]') { unset($bits[$b]); } if ($key == $fullName . '[condition]') { unset($bits[$b]); } } } } $url = $root . '?' . implode('&', $bits); // $$$ rob 24/02/2011 remove duplicates from tags $data = array_unique($data); $img = FabrikWorker::j3() ? 'bookmark.png' : 'tag.png'; $icon = FabrikHelperHTML::image($img, 'form', @$this->tmpl, array('alt' => 'tag')); foreach ($data as $d) { $d = trim($d); if ($d != '') { if (trim($params->get('textarea_tagifyurl')) == '') { $qs = strstr($url, '?'); if (substr($url, -1) === '?') { $thisurl = $url . $name . '[value]=' . $d; } else { $thisurl = strstr($url, '?') ? $url . '&' . $name . '[value]=' . urlencode($d) : $url . '?' . $name . '[value]=' . urlencode($d); } $thisurl .= '&' . $name . '[condition]=CONTAINS'; $thisurl .= '&resetfilters=1'; } else { $thisurl = str_replace('{tag}', urlencode($d), $url); } $tags[] = '<a href="' . $thisurl . '" class="fabrikTag">' . $icon . $d . '</a>'; } } return implode(' ', $tags); }
/** * tagify a string * @param string to tagify * @return string tagified string */ protected function tagify($data) { $name = $this->getFullName(false, true, false); $params = $this->getParams(); $listModel = $this->getlistModel(); $filters = $listModel->getFilterArray(); $fkeys = JArrayHelper::getValue($filters, 'key', array()); $data = explode(",", strip_tags($data)); $tags = array(); $url = $params->get('textarea_tagifyurl'); if ($url == '') { $url = $_SERVER['REQUEST_URI']; $bits = explode('?', $url); $bits = JArrayHelper::getValue($bits, 1, '', 'string'); $bits = explode("&", $bits); foreach ($bits as $bit) { $parts = explode("=", $bit); if (count($parts) > 1) { $key = FabrikString::ltrimword(FabrikString::safeColNameToArrayKey($parts[0]), '&'); if ($key == $this->getFullName(false, true, false)) { $url = str_replace($key . '=' . $parts[1], '', $url); } } } } // $$$ rbo 24/02/2011 remove duplicates from tags $data = array_unique($data); $icon = FabrikHelperHTML::image('tag.png', 'form', @$this->tmpl, array('alt' => 'tag')); foreach ($data as $d) { $d = trim($d); if ($d != '') { if (trim($params->get('textarea_tagifyurl')) == '') { $qs = strstr($url, '?'); if (substr($url, -1) === '?') { $thisurl = "{$url}{$name}={$d}"; } else { $thisurl = strstr($url, '?') ? "{$url}&{$name}=" . urlencode($d) : "{$url}?{$name}=" . urlencode($d); } } else { $thisurl = str_replace('{tag}', urlencode($d), $url); } $tags[] = '<a href="' . $thisurl . '" class="fabrikTag">' . $icon . $d . '</a>'; } } return implode(" ", $tags); }
/** * validate the elements data against the rule * @param string data to check * @param object element Model * @param int plugin sequence ref * @param int repeat group count * @return bol true if validation passes, false if fails */ function validate($data, &$elementModel, $c, $repeat_count = 0) { //could be a dropdown with multivalues if (is_array($data)) { $data = implode('', $data); } $params =& $this->getParams(); $element =& $elementModel->getElement(); $tableModel =& $elementModel->getTableModel(); $table =& $tableModel->getTable(); $db =& $tableModel->getDb(); $lookuptable = $db->nameQuote($table->db_table_name); $data = $db->Quote($data); if ($params->get('isuniquevalue-caseinsensitive') == 1) { $sql = "SELECT COUNT(*) FROM {$lookuptable} WHERE {$element->name} LIKE {$data}"; } else { $sql = "SELECT COUNT(*) FROM {$lookuptable} WHERE {$element->name} = {$data}"; } // $$$ hugh - need to check to see if we're editing a record, otherwise // will fail 'cos it finds the original record (assuming this element hasn't changed) // @TODO - is there a better way getting the rowid? What if this is form a joined table? // $rowid = JRequest::getVar('rowid'); // Have to do it by grabbing PK from request, 'cos rowid isn't set on AJAX validation $pk = FabrikString::safeColNameToArrayKey($table->db_primary_key); $rowid = JRequest::getVar($pk, ''); if (!empty($rowid)) { //if main key is in repeat group! if (is_array($rowid)) { foreach ($rowid as &$i) { $i = $db->Quote($i); } $s = implode(',', $rowid); if ($s !== "''") { $sql .= " AND {$table->db_primary_key} NOT IN (" . $s . ")"; } } else { $sql .= " AND {$table->db_primary_key} != " . $db->Quote($rowid); } } $db->setQuery($sql); $c = $db->loadResult(); return $c == 0 ? true : false; }
/** * Return the javascript to create an instance of the class defined in formJavascriptClass * * @param object $params plugin parameters * @param object $model list model * @param array $args array [0] => string table's form id to contain plugin * * @return bool */ public function onLoadJavascriptInstance($params, $model, $args) { if (!$this->canUse()) { return; } $orderEl = $model->getFormModel()->getElement($params->get('order_element'), true); $form_id = $model->getFormModel()->getId(); $opts = $this->getElementJSOptions($model); $opts->enabled = count($model->orderEls) === 1 && FabrikString::safeColNameToArrayKey($model->orderEls[0]) == FabrikString::safeColNameToArrayKey($orderEl->getOrderByName()) ? true : false; $opts->listid = $model->getId(); $opts->orderElementId = $params->get('order_element'); $opts->handle = $params->get('order_element_as_handle', 1) == 1 ? '.' . $orderEl->getOrderByName() : false; $opts->direction = $opts->enabled ? $model->orderDirs[0] : ''; $opts->transition = ''; $opts->duration = ''; $opts->constrain = ''; $opts->clone = ''; $opts->revert = ''; $opts = json_encode($opts); $this->jsInstance = "new FbListOrder({$opts})"; return true; }
/** * return the javascript to create an instance of the class defined in formJavascriptClass * @param object parameters * @param list table model * @param array [0] => string table's form id to contain plugin * @return bool */ function onLoadJavascriptInstance($params, $model, $args) { parent::onLoadJavascriptInstance($params, $model, $args); FabrikHelperHTML::addStyleDeclaration('.focusClass{border:1px solid red !important;}'); FabrikHelperHTML::script('media/com_fabrik/js/element.js'); $listModel = JModel::getInstance('list', 'FabrikFEModel'); $listModel->setId(JRequest::getVar('listid')); $elements = $model->getElements('filtername'); $pels = $params->get('inline_editable_elements'); $use = trim($pels) == '' ? array() : explode(",", $pels); $els = array(); $srcs = array(); foreach ($elements as $key => $val) { $key = FabrikString::safeColNameToArrayKey($key); if (empty($use) || in_array($key, $use)) { $els[$key] = new stdClass(); $els[$key]->elid = $val->_id; $els[$key]->plugin = $val->getElement()->plugin; //load in all element js classes $val->formJavascriptClass($src); } } FabrikHelperHTML::script($srcs, true); $opts = new stdClass(); $opts->elements = $els; $opts->listid = $model->getId(); $opts->focusClass = 'focusClass'; $opts->editEvent = $params->get('inline_edit_event', 'dblclick'); $opts->tabSave = $params->get('inline_tab_save', false); $opts->showCancel = $params->get('inline_show_cancel', true); $opts->showSave = $params->get('inline_show_save', true); $opts->loadFirst = (bool)$params->get('inline_load_first', false); $opts = json_encode($opts); $formid = 'list_'+$model->getFormModel()->getForm()->id; $this->jsInstance = "new FbListInlineEdit($opts)"; return true; }
/** * return the javascript to create an instance of the class defined in formJavascriptClass * @param object parameters * @param object table model * @param array [0] => string table's form id to contain plugin * @return bool */ function loadJavascriptInstance($params, $model, $args) { $form_id = $args[0]; FabrikHelperHTML::script('element.js', 'media/com_fabrik/js/'); $tableModel =& JModel::getInstance('table', 'FabrikModel'); $tableModel->setId(JRequest::getVar('tableid')); $elements =& $tableModel->getElements('filtername'); $pels = $params->get('inline_editable_elements'); $use = trim($pels) == '' ? array() : explode(",", $pels); $els = array(); foreach ($elements as $key => $val) { $key = FabrikString::safeColNameToArrayKey($key); if (empty($use) || in_array($key, $use)) { $els[$key] = new stdClass(); $els[$key]->elid = $val->_id; $els[$key]->plugin = $val->getElement()->plugin; //load in all element js classes $val->formJavascriptClass(); } } $opts = new stdClass(); $opts->mooversion = FabrikWorker::getMooVersion() == 1 ? 1.2 : 1.1; $opts->elements = $els; $opts->tableid = $tableModel->_id; $opts->focusClass = 'focusClass'; $opts->liveSite = COM_FABRIK_LIVESITE; $opts->editEvent = $params->get('inline_edit_event', 'dblclick'); $opts->tabSave = $params->get('inline_tab_save', false); $opts->showCancel = $params->get('inline_show_cancel', true); $opts->showSave = $params->get('inline_show_save', true); $opts->loadFirst = (bool) $params->get('inline_load_first', false); $opts = json_encode($opts); $lang = $this->_getLang(); $lang = json_encode($lang); $this->jsInstance = "new FbTableInlineEdit('{$form_id}', {$opts}, {$lang})"; return true; }
/** * build the filter query for the given element. * @param $key element name in format `tablename`.`elementname` * @param $condition =/like etc * @param $value search string - already quoted if specified in filter array options * @param $originalValue - original filter value without quotes or %'s applied * @param string filter type advanced/normal/prefilter/search/querystring/searchall * @return string sql query part e,g, "key = value" */ function getFilterQuery($key, $condition, $value, $originalValue, $type = 'normal') { # $$$ rob $this->_rawFilter set in tableModel::getFilterArray() # used in prefilter dropdown in admin to allow users to prefilter on raw db join value $params =& $this->getParams(); if ($type == 'querystring') { $key2 = FabrikString::safeColNameToArrayKey($key); // $$$ rob no matter whether you use elementname_raw or elementname in the querystring filter // by the time it gets here we have normalized to elementname. So we check if the original qs filter was looking at the raw // value if it was then we want to filter on the key and not the label if (!array_key_exists($key2, JRequest::get('get'))) { if (!$this->_rawFilter) { $k = FabrikString::safeColName($params->get('join_db_name') . "." . $params->get('join_key_column')); } else { $k = $key; } $this->encryptFieldName($k); return "{$k} {$condition} {$value}"; } } if (!$this->_rawFilter && ($type == 'searchall' || $type == 'prefilter')) { $key = FabrikString::safeColName($params->get('cascadingdropdown_label')); } $this->encryptFieldName($key); $str = "{$key} {$condition} {$value}"; return $str; }
/** * convert the posted form data to the data to be shown in the email * e.g. radio buttons swap their values for the value's label * * HACKED from the form view * * @return array email data */ function getEmailData() { if (isset($this->emailData)) { return $this->emailData; } $model = $this->formModel; if (is_null($model->_formDataWithTableName)) { return array(); } $model->isAjax(); //$$$rob don't render the form - there's no need and it gives a warning about an unfound rowid // $$$ rob also it sets teh fromModels rowid to an + int even if we are submitting a new form // which means that form plug-ins set to run on new only don't get triggered if they appear after // fabrikemail/fabrikreceipt //Now instead the pk value is taken from the tableModel->lastInsertId and inserted at the end of this method //$model->render(); $listModel = $model->_table; $table = is_object($listModel) ? $listModel->getTable() : null; $model->_editable = false; if (is_object($listModel)) { $joins = $listModel->getJoins(); $model->getJoinGroupIds($joins); } $params = $model->getParams(); $this->emailData = array(); // $$$ hugh - temp foreach fix $groups = $model->getGroupsHiarachy(); foreach ($groups as $gkey => $groupModel) { $groupParams = $groupModel->getParams(); //check if group is acutally a table join $repeatGroup = 1; $foreignKey = null; if ($groupModel->canRepeat()) { if ($groupModel->isJoin()) { $joinModel = $groupModel->getJoinModel(); $joinTable = $joinModel->getJoin(); $foreignKey = ''; if (is_object($joinTable)) { $foreignKey = $joinTable->table_join_key; //need to duplicate this perhaps per the number of times //that a repeat group occurs in the default data? if (array_key_exists($joinTable->id, $model->_formDataWithTableName['join'])) { $elementModels = $groupModel->getPublishedElements(); reset($elementModels); $tmpElement = current($elementModels); $smallerElHTMLName = $tmpElement->getFullName(false, true, false); //$repeatGroup = count($model->_data['join'][$joinTable->id][$smallerElHTMLName]); $repeatGroup = count($model->_formDataWithTableName['join'][$joinTable->id][$smallerElHTMLName]); } else { if (!$groupParams->get('repeat_group_show_first')) { continue; } } } } else { // $$$ rob 19/03/2012 - deprecated? // repeat groups which arent joins /* $elementModels = $groupModel->getPublishedElements(); foreach ($elementModels as $tmpElement) { $smallerElHTMLName = $tmpElement->getFullName(false, true, false); if (is_array($model->_formDataWithTableName)) { if (array_key_exists($smallerElHTMLName."_raw", $model->_formDataWithTableName)) { $d = $model->_formDataWithTableName[$smallerElHTMLName."_raw"]; } else { $d = @$model->_formDataWithTableName[$smallerElHTMLName]; } $d = FabrikWorker::JSONtoData($d, true); $c = count($d); if ($c > $repeatGroup) { $repeatGroup = $c;} } } */ } } $groupModel->repeatTotal = $repeatGroup; $group = $groupModel->getGroup(); $aSubGroups = array(); for ($c = 0; $c < $repeatGroup; $c++) { $aSubGroupElements = array(); $elementModels = $groupModel->getPublishedElements(); foreach ($elementModels as $elementModel) { //force reload? $elementModel->defaults = null; $elementModel->_repeatGroupTotal = $repeatGroup - 1; $element = $elementModel->getElement(); $k = $elementModel->getFullName(false, true, false); $key = $elementModel->getFullName(true, true, false); //used for working out if the element should behave as if it was //in a new form (joined grouped) even when editing a record $elementModel->_inRepeatGroup = $groupModel->canRepeat(); $elementModel->_inJoin = $groupModel->isJoin(); $elementModel->_editable = false; if ($elementModel->_inJoin) { if ($elementModel->_inRepeatGroup) { if (!array_key_exists($k . "_raw", $this->emailData)) { $this->emailData[$k . '_raw'] = array(); } $this->emailData[$k . '_raw'][] = JArrayHelper::getValue($model->_formDataWithTableName['join'][$group->join_id][$k], $c); } else { $this->emailData[$k . '_raw'] = $model->_formDataWithTableName['join'][$group->join_id][$k]; } } else { //@TODO do we need to check if none -joined repeat groups have their data set out correctly? if (array_key_exists($key, $model->_formDataWithTableName)) { $rawval = JArrayHelper::getValue($model->_formDataWithTableName, $k . '_raw', ''); if ($rawval == '') { $this->emailData[$k . '_raw'] = $model->_formDataWithTableName[$key]; } else { // things like the user element only have their raw value filled in at this point // so don't overwrite that with the blank none-raw value // the none-raw value is add in getEmailValue() $this->emailData[$k . '_raw'] = $rawval; } } } // $$$ hugh - need to poke data into $elementModel->_form->_data as it is needed // by CDD getOptions when building the query, to constrain the WHERE clause with // selected FK value. // $$$ rob in repeat join groups this isnt really efficient as you end up reformatting the data $c times $elementModel->_form->_data = $model->_formDataWithTableName; // $$$ hugh - for some reason, CDD keys themselves are missing form emailData, if no selection was made? // (may only be on AJAX submit) $email_value = ''; if (array_key_exists($k . '_raw', $this->emailData)) { $email_value = $this->emailData[$k . '_raw']; } else { if (array_key_exists($k, $this->emailData)) { $email_value = $this->emailData[$k]; } } $this->emailData[$k] = $elementModel->getEmailValue($email_value, $model->_formDataWithTableName, $c); if ($elementModel->_inRepeatGroup && $elementModel->_inJoin) { $this->emailData['join'][$groupModel->getGroup()->join_id][$k . '_raw'] = $this->emailData[$k . '_raw']; $this->emailData['join'][$groupModel->getGroup()->join_id][$k] = $this->emailData[$k]; } } } } $pk = FabrikString::safeColNameToArrayKey($listModel->getTable()->db_primary_key); $this->emailData[$pk] = $listModel->lastInsertId; $this->emailData[$pk . '_raw'] = $listModel->lastInsertId; return $this->emailData; }
/** * get the selected records * @param string $key * @param bool $allData * @return array rows: */ public function getRecords($key = 'ids', $allData = false) { $ids = (array) JRequest::getVar($key, array()); JArrayHelper::toInteger($ids); if (empty($ids)) { JError::raiseError(400, JText::_('PLG_LIST_EMAIL_ERR_NO_RECORDS_SELECTED')); jexit(); } $renderOrder = JRequest::getInt('renderOrder'); $params = $this->getParams(); $model = $this->listModel; $pk = $model->getTable()->db_primary_key; $pk2 = FabrikString::safeColNameToArrayKey($pk) . '_raw'; $whereClause = "({$pk} IN (" . implode(",", $ids) . "))"; $cond = $params->get('emailtable_condition'); $cond = JArrayHelper::getValue($cond, $renderOrder); if (trim($cond) !== '') { $whereClause .= " AND ({$cond})"; } $model->setPluginQueryWhere($this->buttonPrefix, $whereClause); $data = $model->getData(); if ($allData) { return $data; } $return = array(); foreach ($data as $gdata) { foreach ($gdata as $row) { $return[] = $row->{$pk2}; } } return $return; }
/** * 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 $usercol_val = is_array($row) ? $row[$usercol] : $row->{$usercol}; // User element stores as object if (is_object($usercol_val)) { $usercol_val = JArrayHelper::fromObject($usercol_val); } // Could be coming back from a failed validation in which case val might be an array if (is_array($usercol_val)) { $usercol_val = array_shift($usercol_val); } if (empty($usercol_val) && empty($myid)) { return false; } if (intVal($usercol_val) === intVal($myid) || $input->get('rowid') == -1) { return true; } } } } return -1; }
/** * Get the first last, prev and next record ids * * @return object */ protected function getNavIds() { if (isset($this->navIds)) { return $this->navIds; } $formModel = $this->getModel(); $listModel = $formModel->getListModel(); $listModel->filters = null; $filterModel = $listModel->getFilterModel(); $filterModel->destroyRequest(); $this->app->input->set('view', 'list'); $listref = $listModel->getId() . '_com_' . $this->package . '_' . $listModel->getId(); $this->app->input->set('listref', $listref); $table = $listModel->getTable(); $db = $listModel->getDb(); $query = $db->getQuery(true); // As we are selecting on primary key we can select all rows - 3000 records load in 0.014 seconds $query->select($table->db_primary_key)->from($table->db_table_name); $query = $listModel->buildQueryJoin($query); $query = $listModel->buildQueryWhere(true, $query); $query = $listModel->buildQueryOrder($query); foreach ($listModel->orderEls as $orderName) { $orderName = FabrikString::safeColNameToArrayKey($orderName); $query->select(FabrikString::safeColName($orderName) . ' AS ' . $orderName); } $db->setQuery($query); $rows = $db->loadColumn(); $keys = array_flip($rows); $o = new stdClass(); $o->index = FArrayHelper::getValue($keys, $formModel->getRowId(), 0); $o->first = $rows[0]; $o->lastKey = count($rows) - 1; $o->last = $rows[$o->lastKey]; $o->next = $o->index + 1 > $o->lastKey ? $o->lastKey : $rows[$o->index + 1]; $o->prev = $o->index - 1 < 0 ? 0 : $rows[$o->index - 1]; $this->navIds = $o; $this->app->input->set('view', 'form'); return $this->navIds; }
/** * Get the selected records * * @param string $key key * @param bool $allData data * * @return array rows */ public function getRecords($key = 'ids', $allData = false) { $app = JFactory::getApplication(); $input = $app->input; if ($key === 'recordids') { $ids = explode(',', $input->get($key, '', 'string')); } else { $ids = (array) $input->get($key, array(), 'array'); } JArrayHelper::toInteger($ids); if (empty($ids)) { JError::raiseError(400, JText::_('PLG_LIST_EMAIL_ERR_NO_RECORDS_SELECTED')); jexit(); } $renderOrder = $input->getInt('renderOrder'); $params = $this->getParams(); $model = $this->listModel; $pk = $model->getTable()->db_primary_key; $pk2 = FabrikString::safeColNameToArrayKey($pk) . '_raw'; $whereClause = "({$pk} IN (" . implode(",", $ids) . "))"; $cond = $params->get('emailtable_condition'); if (trim($cond) !== '') { $whereClause .= ' AND (' . $cond . ')'; } $model->setPluginQueryWhere($this->buttonPrefix, $whereClause); $data = $model->getData(); if ($allData) { return $data; } $return = array(); foreach ($data as $gdata) { foreach ($gdata as $row) { $return[] = $row->{$pk2}; } } return $return; }
/** * 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 * * @param object $params plugin params * @param object &$formModel form model * * @return bool */ public function onAfterProcess($params, &$formModel) { $app = JFactory::getApplication(); $data = $formModel->_fullFormData; $this->data = $data; JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_fabrik/tables'); $log = FabTable::getInstance('log', 'FabrikTable'); if (!$this->shouldProcess('paypal_conditon', $data, $formModel)) { return true; } $this->formModel = $formModel; $emailData = $this->getEmailData(); $w = new FabrikWorker(); $user = JFactory::getUser(); $userid = $user->get('id'); $ipn = $this->getIPNHandler($params); if ($ipn !== false) { if (method_exists($ipn, 'createInvoice')) { $ipn->createInvoice(); } } $paypal_testmode = $params->get('paypal_testmode', false); $url = $paypal_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 = $params->get('paypal_accountemail'); if (trim($email) == '') { $email = $emailData[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, $data); // @TODO Hugh/Rob check $$$tom: 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. if ($params->get('paypal_cost_eval', 0) == 1) { $amount = @eval($amount); } if (trim($amount) == '') { $amount = JArrayHelper::getValue($emailData, FabrikString::safeColNameToArrayKey($params->get('paypal_cost_element'))); if (is_array($amount)) { $amount = array_shift($amount); } } $opts['amount'] = "{$amount}"; // $$$tom added Shipping Cost params $shipping_amount = $params->get('paypal_shipping_cost'); if ($params->get('paypal_shipping_cost_eval', 0) == 1) { $shipping_amount = @eval($shipping_amount); } if (trim($shipping_amount) == '') { $shipping_amount = JArrayHelper::getValue($emailData, FabrikString::safeColNameToArrayKey($params->get('paypal_shipping_cost_element'))); if (is_array($shipping_amount)) { $shipping_amount = array_shift($shipping_amount); } } $opts['shipping'] = "{$shipping_amount}"; $item = $params->get('paypal_item'); $item = $w->parseMessageForPlaceHolder($item, $emailData); if ($params->get('paypal_item_eval', 0) == 1) { $item = @eval($item); $item_raw = $item; } if (trim($item) == '') { $item_raw = JArrayHelper::getValue($emailData, FabrikString::safeColNameToArrayKey($params->get('paypal_item_element') . '_raw')); $item = $emailData[FabrikString::safeColNameToArrayKey($params->get('paypal_item_element'))]; if (is_array($item)) { $item = array_shift($item); } } // $$$ 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 ($opts['cmd'] === '_xclick-subscriptions') { $subTable = JModel::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->quote($item_raw) . ' AS item_number')->from($subTable->getTable()->db_table_name)->where($idEl . ' = ' . $subDb->quote($item_raw)); $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'] = ''; $tmp = array_merge(JRequest::get('data'), JArrayHelper::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 { JError::raiseError(500, 'Could not determine subscription period, please check your settings'); } } /* $$$ rob 03/02/2011 * check if we have a gateway subscription switch set up. This is for sites where * you can toggle between a subscription or a single payment. E.g. fabrikar com * if 'paypal_subscription_switch' is blank then use the $opts['cmd'] setting * if not empty it should be some eval'd PHP which needs to return true for the payment * to be treated as a subscription * We want to do this so that single payments can make use of Paypals option to pay via credit card * without a paypal account (subscriptions require a Paypal account) * We do this after the subscription code has been run as this code is still needed to look up the correct item_name */ $subSwitch = $params->get('paypal_subscription_switch'); if (trim($subSwitch) !== '') { $subSwitch = $w->parseMessageForPlaceHolder($subSwitch); $isSub = @eval($subSwitch); if (!$isSub) { // 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']); } } /* @TODO Hugh/Rob check $$$tom: Adding shipping options * Currently the admin select a user element on the form to compare it to the user id on the custom user table * Should we just make it to get the current user ID and use that? * $shipping_userid = $data[FabrikString::safeColNameToArrayKey($params->get('paypal_shipping_userelement') )]; * if (is_array($shipping_userid)) { * $shipping_userid = array_shift($shipping_userid); *} */ $shipping_userid = $userid; if ($shipping_userid > 0) { $shipping_select = array(); $db = FabrikWorker::getDbo(); // $$$tom Surely there's a better Fabrik way of getting the table name... $query = $db->getQuery(true); $query->select('db_table_name')->from('#__{package}_lists')->where('id = ' . (int) $params->get('paypal_shippingdata_table')); $db->setQuery($query); $shipping_table = $db->loadResult(); if ($params->get('paypal_shippingdata_firstname')) { $shipping_first_name = FabrikString::shortColName($params->get('paypal_shippingdata_firstname')); $shipping_select['first_name'] = $shipping_first_name; } if ($params->get('paypal_shippingdata_lastname')) { $shipping_last_name = FabrikString::shortColName($params->get('paypal_shippingdata_lastname')); $shipping_select['last_name'] = $shipping_last_name; } if ($params->get('paypal_shippingdata_address1')) { $shipping_address1 = FabrikString::shortColName($params->get('paypal_shippingdata_address1')); $shipping_select['address1'] = $shipping_address1; } if ($params->get('paypal_shippingdata_address2')) { $shipping_address2 = FabrikString::shortColName($params->get('paypal_shippingdata_address2')); $shipping_select['address2'] = $shipping_address2; } if ($params->get('paypal_shippingdata_zip')) { $shipping_zip = FabrikString::shortColName($params->get('paypal_shippingdata_zip')); $shipping_select['zip'] = $shipping_zip; } if ($params->get('paypal_shippingdata_state')) { $shipping_state = FabrikString::shortColName($params->get('paypal_shippingdata_state')); $shipping_select['state'] = $shipping_state; } if ($params->get('paypal_shippingdata_city')) { $shipping_city = FabrikString::shortColName($params->get('paypal_shippingdata_city')); $shipping_select['city'] = $shipping_city; } if ($params->get('paypal_shippingdata_country')) { $shipping_country = FabrikString::shortColName($params->get('paypal_shippingdata_country')); $shipping_select['country'] = $shipping_country; } $query->clear(); $query->select($shipping_select)->from($shipping_table)->where(FabrikString::shortColName($params->get('paypal_shippingdata_id')) . ' = ' . $db->quote($shipping_userid)); $db->setQuery($query); $user_shippingdata = $db->loadObject(); foreach ($shipping_select 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] = $user_shippingdata->{$val}; } } } if ($params->get('paypal_shipping_address_override', 0)) { $opts['address_override'] = 1; } $paypal_currency_code = $params->get('paypal_currencycode', 'USD'); $paypal_currency_code = $w->parseMessageForPlaceHolder($paypal_currency_code, $data); $opts['currency_code'] = $paypal_currency_code; $paypal_test_site = $params->get('paypal_test_site', ''); $paypal_test_site = rtrim($paypal_test_site, '/'); if ($paypal_testmode == 1 && !empty($paypal_test_site)) { $ppurl = $paypal_test_site . '/index.php?option=com_fabrik&c=plugin&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=ipn'; } else { $ppurl = COM_FABRIK_LIVESITE . '/index.php?option=com_fabrik&c=plugin&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=ipn'; } $paypal_test_site_qs = $params->get('paypal_test_site_qs', ''); if ($paypal_testmode == 1 && !empty($paypal_test_site_qs)) { $ppurl .= $paypal_test_site_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, $data); if ($paypal_testmode == 1 && !empty($paypal_return_url)) { if (preg_match('#^http:\\/\\/#', $paypal_return_url)) { $opts['return'] = $paypal_return_url; } else { if (!empty($paypal_test_site)) { $opts['return'] = $paypal_test_site . '/' . $paypal_return_url; } else { $opts['return'] = COM_FABRIK_LIVESITE . '/' . $paypal_return_url; } } if (!empty($paypal_test_site_qs)) { $opts['return'] .= $paypal_test_site_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 ($paypal_testmode == '1' && !empty($paypal_test_site)) { $opts['return'] = $paypal_test_site . '/index.php?option=com_fabrik&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=thanks&rowid=' . $data['rowid'] . '&renderOrder=' . $this->renderOrder; } else { $opts['return'] = COM_FABRIK_LIVESITE . '/index.php?option=com_fabrik&task=plugin.pluginAjax&formid=' . $formModel->get('id') . '&g=form&plugin=paypal&method=thanks&rowid=' . $data['rowid'] . '&renderOrder=' . $this->renderOrder; } } $opts['return'] = urlencode($opts['return']); $ipn_value = $params->get('paypal_ipn_value', ''); $ipn_value = $w->parseMessageForPlaceHolder($ipn_value, $data); // Extra :'s will break parsing during IPN notify phase $ipn_value = str_replace(':', ';', $ipn_value); // $$$ 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 $log->message_type = 'fabrik.paypal.onAfterProcess'; $msg = new stdClass(); $msg->opt = $opts; $msg->data = $data; $msg->msg = "Submission cancelled by checkOpts!"; $log->message = json_encode($msg); $log->store(); return true; } } } $opts['custom'] = $data['formid'] . ':' . $data['rowid'] . ':' . $ipn_value; $qs = array(); foreach ($opts as $k => $v) { $qs[] = "{$k}={$v}"; } $url .= implode('&', $qs); /* $$$ rob 04/02/2011 no longer doing redirect from ANY plugin EXCEPT the redirect plugin * - instead a session var is set (com_fabrik.form.X.redirect.url) * as the preferred redirect url */ $session = JFactory::getSession(); $context = $formModel->getRedirectContext(); /* $$$ hugh - fixing issue with new redirect, which now needs to be an array. * Not sure if we need to preserve existing session data, or just create a new surl array, * to force ONLY recirect to PayPal? */ $surl = (array) $session->get($context . 'url', array()); $surl[$this->renderOrder] = $url; $session->set($context . 'url', $surl); $session->set($context . 'redirect_content_how', 'samepage'); // Log the info $log->message_type = 'fabrik.paypal.onAfterProcess'; $msg = new stdClass(); $msg->opt = $opts; $msg->data = $data; $log->message = json_encode($msg); $log->store(); return true; }
/** * Load the JavaScript ini options * * @since 3.1b * * @return stdClass */ protected function jsOpts() { $input = $this->app->input; /** @var FabrikFEModelForm $model */ $model = $this->getModel(); $fbConfig = JComponentHelper::getParams('com_fabrik'); $form = $model->getForm(); $params = $model->getParams(); $listModel = $model->getlistModel(); $table = $listModel->getTable(); $opts = new stdClass(); $opts->admin = $this->app->isAdmin(); $opts->ajax = $model->isAjax(); $opts->ajaxValidation = (bool) $params->get('ajax_validations'); $opts->showLoader = (bool) $params->get('show_loader_on_submit', '0'); $key = FabrikString::safeColNameToArrayKey($table->db_primary_key); $opts->primaryKey = $key; $opts->error = @$form->origerror; $opts->pages = $model->getPages(); $opts->plugins = array(); $opts->multipage_save = (int) $model->saveMultiPage(); $opts->editable = $model->isEditable(); $opts->print = (bool) $input->getInt('print'); $startPage = isset($model->sessionModel->last_page) ? (int) $model->sessionModel->last_page : 0; if ($startPage !== 0) { $this->app->enqueueMessage(FText::_('COM_FABRIK_RESTARTING_MULTIPAGE_FORM')); } else { // Form submitted but fails validation - needs to go to the last page $startPage = $input->getInt('currentPage', 0); } $opts->start_page = $startPage; $opts->inlineMessage = (bool) $this->isMambot; // $$$rob don't int this as keys may be string $opts->rowid = (string) $model->getRowId(); // 3.0 needed for ajax requests $opts->listid = (int) $this->get('ListModel')->getId(); $errorIcon = FabrikWorker::j3() ? $fbConfig->get('error_icon', 'exclamation-sign') . '.png' : 'alert.png'; $this->errorIcon = FabrikHelperHTML::image($errorIcon, 'form', $this->tmpl); $imgs = new stdClass(); $imgs->alert = FabrikHelperHTML::image($errorIcon, 'form', $this->tmpl, '', true); $imgs->action_check = FabrikHelperHTML::image('action_check.png', 'form', $this->tmpl, '', true); $imgs->ajax_loader = FabrikHelperHTML::image('ajax-loader.gif', 'form', $this->tmpl, '', true); $imgs->ajax_loader = FabrikHelperHTML::icon('icon-spinner icon-spin'); $opts->images = $imgs; // $$$rob if you are loading a list in a window from a form db join select record option // then we want to know the id of the window so we can set its showSpinner() method // 3.0 changed to fabrik_window_id (automatically appended by Fabrik.Window xhr request to load window data $opts->fabrik_window_id = $input->get('fabrik_window_id', ''); $opts->submitOnEnter = (bool) $params->get('submit_on_enter', false); // For editing groups with joined data and an empty joined record (i.e. no joined records) $hidden = array(); $maxRepeat = array(); $minRepeat = array(); $showMaxRepeats = array(); $minMaxErrMsg = array(); foreach ($this->groups as $g) { $hidden[$g->id] = $g->startHidden; $maxRepeat[$g->id] = $g->maxRepeat; $minRepeat[$g->id] = $g->minRepeat; $showMaxRepeats[$g->id] = $g->showMaxRepeats; $minMaxErrMsg[$g->id] = $g->minMaxErrMsg; } $opts->hiddenGroup = $hidden; $opts->maxRepeat = $maxRepeat; $opts->minRepeat = $minRepeat; $opts->showMaxRepeats = $showMaxRepeats; $opts->minMaxErrMsg = $minMaxErrMsg; // $$$ hugh adding these so calc element can easily find joined and repeated join groups // when it needs to add observe events ... don't ask ... LOL! $opts->join_group_ids = array(); $opts->group_repeats = array(); $opts->group_joins_ids = array(); $groups = $model->getGroupsHiarachy(); foreach ($groups as $groupModel) { if ($groupModel->getGroup()->is_join) { $joinParams = $groupModel->getJoinModel()->getJoin()->params; if (!is_a($joinParams, 'JRegistry')) { $joinParams = new JRegistry($joinParams); } $groupId = $groupModel->getGroup()->id; $opts->group_pk_ids[$groupId] = FabrikString::safeColNameToArrayKey($joinParams->get('pk')); $opts->join_group_ids[$groupModel->getGroup()->join_id] = (int) $groupModel->getGroup()->id; $opts->group_join_ids[$groupId] = (int) $groupModel->getGroup()->join_id; $opts->group_repeats[$groupId] = $groupModel->canRepeat(); $opts->group_copy_element_values[$groupId] = $groupModel->canCopyElementValues(); $opts->group_repeat_intro[$groupId] = $groupModel->getParams()->get('repeat_intro', ''); } } return $opts; }
/** * validate the passwords * @param string elements data * @param int repeat group counter * @return bol true if passes / false if falise validation */ function validate($data, $repeatCounter = 0) { $k = $this->getlistModel()->getTable()->db_primary_key; $k = FabrikString::safeColNameToArrayKey($k); $post = JRequest::get('post'); $this->defaults = null; $element = $this->getElement(); $origname = $element->name; $element->name = $element->name . "_check"; $checkvalue = $this->getValue($post, $repeatCounter); $element->name = $origname; if ($checkvalue != $data) { $this->_validationErr = JText::_('PLG_ELEMENT_PASSWORD_PASSWORD_CONFIRMATION_DOES_NOT_MATCH'); return false; } else { //$$$ rob add rowid test as well as if using row=-1 and usekey=field $k may have a value if (JRequest::getInt('rowid') === 0 && JRequest::getInt($k, 0, 'post') === 0 && $data === '') { $this->_validationErr .= JText::_('PLG_ELEMENT_PASSWORD_PASSWORD_CONFIRMATION_EMPTY_NOT_ALLOWED'); return false; } return true; } }
/** * Called via ajax nav * * @param int $dir 1 - move forward, 0 move back * * @return bool new row id loaded. */ public function paginateRowId($dir) { $db = FabrikWorker::getDbo(); $input = $this->app->input; $c = $dir == 1 ? '>=' : '<='; $intLimit = $dir == 1 ? 2 : 0; $listModel = $this->getListModel(); $item = $listModel->getTable(); $rowId = $input->getString('rowid', '', 'string'); $query = $db->getQuery(true); $query->select($item->db_primary_key . ' AS ' . FabrikString::safeColNameToArrayKey($item->db_primary_key))->from($item->db_table_name)->where($item->db_primary_key . ' ' . $c . ' ' . $db->q($rowId)); $query = $listModel->buildQueryOrder($query); $db->setQuery($query, 0, $intLimit); $ids = $db->loadColumn(); if ($dir == 1) { if (count($ids) >= 2) { $input->set('rowid', $ids[$dir]); return true; } else { return false; } } if (count($ids) - 2 >= 0) { $input->set('rowid', $ids[count($ids) - 2]); return true; } return false; }
/** * Build the sums() sql statement * * @return string */ private function sums() { $params = $this->getParams(); $sums = explode(',', $params->get('pivot_sum')); $db = $this->model->getDb(); $fn = (int) $params->get('pivot_count', '0') == 1 ? 'COUNT' : 'SUM'; foreach ($sums as &$sum) { $sum = trim($sum); $sum = FabrikString::rtrimword($sum, '_raw'); $as = FabrikString::safeColNameToArrayKey($sum); $statement = $fn . '(' . FabrikString::safeColName($sum) . ')'; $statement .= ' AS ' . $db->quoteName($as); $statement .= ', ' . $fn . '(' . FabrikString::safeColName($sum) . ')'; $statement .= ' AS ' . $db->quoteName($as . '_raw'); $sum = $statement; } $sum = implode(', ', $sums); return $sum; }
/** * Get the selected records * * @param string $key key * @param bool $allData data * * @return array rows */ public function getRecords($key = 'ids', $allData = false) { $params = $this->getParams(); $model = $this->listModel; $input = $this->app->input; $pk = $model->getPrimaryKey(); $pk2 = FabrikString::safeColNameToArrayKey($pk) . '_raw'; /** * If the 'checkall' param is set, and the checkAll checkbox was used, ignore pagination and selected * ids, and just select all rows, subject to filtering. * * If not doing 'checkall', use the selected ids as usual. */ if ($input->get('checkAll', '0') == '1' && $params->get('checkall', '0') == '1') { $whereClause = ''; } else { if ($key === 'recordids') { $ids = explode(',', $input->get($key, '', 'string')); } else { $ids = (array) $input->get($key, array(), 'array'); } $ids = ArrayHelper::toInteger($ids); if (empty($ids)) { throw new RuntimeException(FText::_('PLG_LIST_EMAIL_ERR_NO_RECORDS_SELECTED'), 400); } $whereClause = '(' . $pk . ' IN (' . implode(',', $ids) . '))'; } $cond = $params->get('emailtable_condition'); if (trim($cond) !== '') { if (!empty($whereClause)) { $whereClause .= ' AND '; } $whereClause .= '(' . $cond . ')'; } $model->setLimits(0, -1); $model->setPluginQueryWhere($this->buttonPrefix, $whereClause); $data = $model->getData(); if ($allData) { return $data; } $return = array(); foreach ($data as $gdata) { foreach ($gdata as $row) { $return[] = $row->{$pk2}; } } return $return; }
/** * Show the add event form * * @return void */ public function addEvForm() { $app = JFactory::getApplication(); $package = $app->getUserState('com_fabrik.package', 'fabrik'); $input = $app->input; $listid = $input->getInt('listid'); $viewName = 'calendar'; $usersConfig = JComponentHelper::getParams('com_fabrik'); $model = $this->getModel($viewName); $id = $input->getInt('visualizationid', $usersConfig->get('visualizationid', 0)); $model->setId($id); $model->setupEvents(); $config = JFactory::getConfig(); $prefix = $config->get('dbprefix'); if (array_key_exists($listid, $model->events)) { $datefield = $model->events[$listid][0]['startdate']; } else { $datefield = $prefix . 'fabrik_calendar_events___start_date'; } $datefield = FabrikString::safeColNameToArrayKey($datefield); $rowid = $input->getString('rowid', '', 'string'); $listModel = JModelLegacy::getInstance('list', 'FabrikFEModel'); $listModel->setId($listid); $table = $listModel->getTable(); $input->set('view', 'form'); $input->set('formid', $table->form_id); $input->set('tmpl', 'component'); $input->set('ajax', '1'); $nextView = $input->get('nextview', 'form'); $link = 'index.php?option=com_' . $package . '&view=' . $nextView . '&formid=' . $table->form_id . '&rowid=' . $rowid . '&tmpl=component&ajax=1'; $link .= '&' . $prefix . 'fabrik_calendar_events___visualization_id=' . $input->getInt($prefix . 'fabrik_calendar_events___visualization_id'); $link .= '&fabrik_window_id=' . $input->get('fabrik_window_id'); $start_date = $input->getString('start_date', ''); if (!empty($start_date)) { $link .= "&{$datefield}=" . $start_date; } // $$$ rob have to add this to stop the calendar filtering itself after adding an new event? $link .= '&clearfilters=1'; $this->setRedirect($link); }
/** * Is the element selected for either 'OR user edit' or 'OR use delete' acl * * @param string $name Element full name * * @return boolean */ public function isUserDoElement($name) { $acl_types = array('allow_edit_details2', 'allow_delete2'); $params = $this->getParams(); foreach ($acl_types as $acl_type) { $userDoCol = $params->get($acl_type, ''); if ($userDoCol != '') { $userDoCol = FabrikString::safeColNameToArrayKey($userDoCol); if ($userDoCol == $name) { return true; } } } return false; }
public function getRecords($key = 'ids', $allData = false) { $ids = (array) JRequest::getVar($key, array()); $renderOrder = JRequest::getInt('renderOrder'); $params =& $this->getParams(); $model = JModel::getInstance('table', 'FabrikModel'); $model->setId(JRequest::getInt('id')); $pk = $model->getTable()->db_primary_key; $pk2 = FabrikString::safeColNameToArrayKey($pk) . '_raw'; $whereClause = "({$pk} IN (" . implode(",", $ids) . "))"; $cond = $params->get('emailtable_condition'); $cond = is_array($cond) ? JArrayHelper::getValue($cond, $renderOrder, '') : $cond; if (trim($cond) !== '') { $whereClause .= " AND ({$cond})"; } $model->setPluginQueryWhere($this->_buttonPrefix, $whereClause); $model->formatAll(true); $data = $model->getData(); if ($allData) { return $data; } $return = array(); foreach ($data as $gdata) { foreach ($gdata as $row) { $return[] = $row->{$pk2}; } } return $return; }
/** * called via ajax nav * @param int $dir (1 - move foward, 0 move back) * @return bol new row id loaded. */ function paginateRowId($dir) { $db = FabrikWorker::getDbo(); $c = $dir == 1 ? '>=' : '<='; $limit = $dir == 1 ? 'LIMIT 2' : ''; $intLimit = $dir == 1 ? 2 : 0; $listModel = $this->getListModel(); $order = $listModel->_buildQueryOrder(); $item = $listModel->getTable(); $rowid = JRequest::getInt('rowid'); $query = $db->getQuery(true); $query->select($item->db_primary_key . ' AS ' . FabrikString::safeColNameToArrayKey($item->db_primary_key))->from($item->db_table_name)->where($item->db_primary_key . ' ' . $c . ' ' . $rowid); $query = $listModel->_buildQueryOrder($query); $db->setQuery($query, 0, $intLimit); $ids = $db->loadColumn(); if ($dir == 1) { if (count($ids) >= 2) { JRequest::setVar('rowid', $ids[$dir]); return true; } else { return false; } } if (count($ids) - 2 >= 0) { JRequest::setVar('rowid', $ids[count($ids) - 2]); return true; } return false; }
/** * do the plugin action * */ function process(&$data, &$tableModel) { //jimport('joomla.mail.helper'); $params =& $this->getParams(); $app =& Jfactory::getApplication(); $gcal_url = $params->get('gcal_sync_gcal_url'); $matches = array(); // this matches a standard GCal URL, found under the Google "Calender Details" tab, using the XML button. // It should match any form, for public or private ... // http://www.google.com/calendar/feeds/hugh.messenger%40gmail.com/public/basic // http://www.google.com/calendar/feeds/hugh.messenger%40gmail.com/private-3081eca2b0asdfasdf8f106ea6f63343056/basic $gcal_url = str_replace('/basic', '/full', $gcal_url); $gcal_url = preg_replace('#/private-\\w+/#', '/private/', $gcal_url); if (preg_match('#feeds/(.*?)/(\\w+-\\w+|\\w+)/(\\w+)#', $gcal_url, $matches)) { // grab the bits of the URL we need for the Zend framework call $gcal_user = $matches[1]; $gcal_visibility = $matches[2]; $gcal_projection = $matches[3]; $gcal_email = urldecode($gcal_user); // grab the table model and find table name and PK $table =& $tableModel->getTable(); $table_name = $table->db_table_name; $primary_key = $table->db_primary_key; $primary_key_element_long = FabrikString::safeColNameToArrayKey($table->db_primary_key); // for now, we have to read the table ourselves. We can't rely on the $data passed to us // because it can be filtered, and we need to see all records to know if the GCal events // already exist in the table /* $mydata = array(); $db = JFactory::getDBO(); $db->setQuery("SELECT * FROM $table_name"); $mydata[0] = $db->loadObjectList(); */ $db = JFactory::getDBO(); $mydata =& $data; // grab all the field names to use $gcal_label_element_long = $params->get('gcal_sync_label_element'); $gcal_label_element = FabrikString::shortColName($gcal_label_element_long); $gcal_desc_element_long = $params->get('gcal_sync_desc_element'); $gcal_desc_element = FabrikString::shortColName($gcal_desc_element_long); $gcal_start_date_element_long = $params->get('gcal_sync_startdate_element'); $gcal_start_date_element = FabrikString::shortColName($gcal_start_date_element_long); $gcal_end_date_element_long = $params->get('gcal_sync_enddate_element'); $gcal_end_date_element = FabrikString::shortColName($gcal_end_date_element_long); $gcal_id_element_long = $params->get('gcal_sync_id_element'); $gcal_id_element = FabrikString::shortColName($gcal_id_element_long); $gcal_userid_element_long = $params->get('gcal_sync_userid_element'); $gcal_userid_element = FabrikString::shortColName($gcal_userid_element_long); // sanity check, make sure required elements have been specified if (empty($gcal_label_element_long) || empty($gcal_start_date_element_long) || empty($gcal_end_date_element_long) || empty($gcal_id_element_long)) { JError::raiseNotice(500, 'missing gcal data'); return; } // if they selected a User ID element to use, see if we can find a J! user with matching email to this feed's owner $our_userid = 0; if ($gcal_userid_element_long) { $db->setQuery("SELECT id FROM " . $db->nameQuote('#__users') . " WHERE " . $db->nameQUote('email') . " = " . $db->Quote($gcal_email)); $our_userid = $db->loadResult(); // better make sure it's not NULL, in case underlying column is NOT NULL if (empty($our_userid)) { $our_userid = 0; } } // include the Zend stuff $path = JPATH_SITE . DS . 'libraries'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); $path = get_include_path(); require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata'); Zend_Loader::loadClass('Zend_Uri_Http'); // Won't need these loaded until we add sync'ing events back to Google //Zend_Loader::loadClass('Zend_Gdata_AuthSub'); //Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); Zend_Loader::loadClass('Zend_Gdata_Calendar'); // see if they want to sync to gcal, and provided a login $gcal_sync_upload = $params->get('gcal_sync_upload_events', 'from'); if ($gcal_sync_upload == 'both' || $gcal_sync_upload == 'to') { Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); $email = $params->get('gcal_sync_login', ''); $passwd = $params->get('gcal_sync_passwd', ''); try { $client = Zend_Gdata_ClientLogin::getHttpClient($email, $passwd, 'cl'); } catch (Zend_Gdata_App_CaptchaRequiredException $cre) { echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n"; echo 'Token ID: ' . $cre->getCaptchaToken() . "\n"; return; } catch (Zend_Gdata_App_AuthException $ae) { echo 'Problem authenticating: ' . $ae->exception() . "\n"; return; } $gdataCal = new Zend_Gdata_calendar($client); } else { $gdataCal = new Zend_Gdata_calendar(); } // set up and execute the call to grab the feed from google $query = $gdataCal->newEventQuery(); $query->setUser($gcal_user); $query->setVisibility($gcal_visibility); $query->setProjection($gcal_projection); $eventFeed = $gdataCal->getCalendarEventFeed($query); // build an array of the events from the feed, indexed by the Google ID $event_ids = array(); foreach ($eventFeed as $key => $event) { $short_id = $this->_getGcalShortId($event->id->text); $gcal_event_ids[$short_id] =& $eventFeed[$key]; } // run through our table data, and build an array of our events indexed by the Google ID // (of course not all events may have a Google ID) $our_event_ids = array(); $our_upload_ids = array(); foreach ($mydata as $gkey => $group) { if (is_array($group)) { foreach ($group as $rkey => $row) { if ($row->{$gcal_id_element_long}) { $our_event_ids[$row->{$gcal_id_element_long}] =& $mydata[$gkey][$rkey]; } else { $our_upload_ids[] =& $mydata[$gkey][$rkey]; } } } } // now go through the google events id's, and process the ones which aren't in our table. $our_event_adds = array(); foreach ($gcal_event_ids as $id => $event) { if (!array_key_exists($id, $our_event_ids)) { // we don't have the ID, so add the event to our table $row = array(); $row[$gcal_start_date_element_long] = strftime('%Y-%m-%d %H:%M:%S', strtotime($event->when[0]->startTime)); if ($gcal_end_date_element_long) { $row[$gcal_end_date_element_long] = strftime('%Y-%m-%d %H:%M:%S', strtotime($event->when[0]->endTime)); } $row[$gcal_label_element_long] = $event->title->text; if ($gcal_desc_element_long) { $row[$gcal_desc_element_long] = $event->content->text; } $row[$gcal_id_element_long] = $id; if ($gcal_userid_element_long) { $row[$gcal_userid_element_long] = $our_userid; } $tableModel->storeRow($row, 0); } $our_event_adds[$id] = $row; } $app->enqueueMessage(count($our_event_adds) . ' events added '); // if upload syncing (from us to gcal) is enabled ... if ($gcal_sync_upload == 'both' || $gcal_sync_upload == 'to') { // Grab the tzOffset. Note that gcal want +/-XX (like -06) // but J! gives us +/-X (like -6) so we sprintf it to the right format $config =& JFactory::getConfig(); $tzOffset = (int) $config->getValue('config.offset'); $tzOffset = sprintf('%+03d', $tzOffset); // loop thru the array we built earlier of events we have that aren't in gcal $uploadCount = 0; foreach ($our_upload_ids as $id => $event) { // skip if a userid element is specified, and doesn't match the owner of this gcal if ($gcal_userid_element_long) { if ($event->{$gcal_userid_element_long} != $our_userid) { continue; } } // now start building the gcal event structure $newEvent = $gdataCal->newEventEntry(); $newEvent->title = $gdataCal->newTitle($event->{$gcal_label_element_long}); if ($gcal_desc_element_long) { $newEvent->content = $gdataCal->newContent($event->{$gcal_desc_element_long}); } else { $newEvent->content = $gdataCal->newContent($event->{$gcal_label_element_long}); } $when = $gdataCal->newWhen(); // grab the start date, apply the tx offset, and format it for gcal $start_date = JFactory::getDate($event->{$gcal_start_date_element_long}); $start_date->setOffset($tzOffset); $start_fdate = $start_date->toFormat('%Y-%m-%d %H:%M:%S'); $date_array = explode(' ', $start_fdate); $when->startTime = "{$date_array[0]}T{$date_array[1]}.000{$tzOffset}:00"; // we have to provide an end date for gcal, so if we don't have one, // default it to start date + 1 hour if (empty($gcal_end_date_element_long) || empty($event->{$gcal_end_date_element_long}) || $event->{$gcal_end_date_element_long} == '0000-00-00 00:00:00') { $startstamp = strtotime($event->{$gcal_start_date_element_long}); $endstamp = $startstamp + 60 * 60; $event->{$gcal_end_date_element_long} = strftime('%Y-%m-%d %H:%M:%S', $endstamp); } // grab the end date, apply the tx offset, and format it for gcal $end_date = JFactory::getDate($event->{$gcal_end_date_element_long}); $end_date->setOffset($tzOffset); $end_fdate = $end_date->toFormat('%Y-%m-%d %H:%M:%S'); $date_array = explode(' ', $end_fdate); $when->endTime = "{$date_array[0]}T{$date_array[1]}.000{$tzOffset}:00"; $newEvent->when = array($when); // fire off the insertEvent to gcal, catch any errors try { $retEvent = $gdataCal->insertEvent($newEvent, $gcal_url); } catch (Zend_Gdata_App_HttpException $he) { $errStr = 'Problem adding event: ' . $he->getRawResponseBody() . "\n"; continue; } $uploadCount++; // insertEvent worked, so grab the gcal ID from the returned event data, // and update our event record with the short version of the ID $gcal_id = $this->_getGcalShortId($retEvent->id->text); $our_id = $event->__pk_val; $db->setQuery("\n\t\t\t\t\t\tUPDATE {$table_name}\n\t\t\t\t\t\tSET {$gcal_id_element} = " . $db->Quote($gcal_id) . "\n\t\t\t\t\t\tWHERE {$primary_key} = " . (int) $our_id); $db->query(); } $app->enqueueMessage($uploadCount . ' events uploaded to GCal'); } } else { JError::raiseNotice(500, 'Incorrect url'); } }
protected function filterHiddenFields() { $params =& $this->getParams(); $elName = FabrikString::safeColNameToArrayKey($this->getFilterFullName()); $return = "\n<input type=\"hidden\" name=\"" . $elName . "[join_db_name]\" value=\"" . $params->get('join_db_name') . "\"/>"; $return .= "\n<input type=\"hidden\" name=\"" . $elName . "[join_key_column]\" value=\"" . $params->get('join_key_column') . "\"/>"; $return .= "\n<input type=\"hidden\" name=\"" . $elName . "[join_val_column]\" value=\"" . $params->get('join_val_column') . "\"/>"; return $return; }
/** * Get base tag url * * @param string $fullName Full name (key value to remove from querystring) * @param string $rootUrl Optional root to use rather than REQUEST_URI * * @return string */ public static function tagBaseUrl($fullName, $rootUrl = null) { $url = filter_var(ArrayHelper::getValue($_SERVER, 'REQUEST_URI', 'index.php'), FILTER_SANITIZE_URL); $bits = explode('?', $url); $root = isset($rootUrl) ? $rootUrl : FArrayHelper::getValue($bits, 0, '', 'string'); $bits = FArrayHelper::getValue($bits, 1, '', 'string'); $bits = explode("&", $bits); for ($b = count($bits) - 1; $b >= 0; $b--) { $parts = explode("=", $bits[$b]); if (count($parts) > 1) { $key = FabrikString::ltrimword(FabrikString::safeColNameToArrayKey($parts[0]), '&'); if ($key == $fullName) { unset($bits[$b]); } if ($key == $fullName . '[value]') { unset($bits[$b]); } if ($key == $fullName . '[condition]') { unset($bits[$b]); } } } $url = $root . '?' . implode('&', $bits); return $url; }
/** * build the filter query for the given element. * @param $key element name in format `tablename`.`elementname` * @param $condition =/like etc * @param $value search string - already quoted if specified in filter array options * @param $originalValue - original filter value without quotes or %'s applied * @param string filter type advanced/normal/prefilter/search/querystring/searchall * @return string sql query part e,g, "key = value" */ function getFilterQuery($key, $condition, $value, $originalValue, $type = 'normal') { if (!$this->inJDb()) { return "{$key} {$condition} {$value}"; } $element = $this->getElement(); // $$$ hugh - we need to use the join alias, not hard code #__users $join =& $this->getJoin(); $joinTableName = $join->table_join_alias; if (empty($joinTableName)) { $joinTableName = '#__users'; } if ($type == 'querystring') { $key = FabrikString::safeColNameToArrayKey($key); // $$$ rob no matter whether you use elementname_raw or elementname in the querystring filter // by the time it gets here we have normalized to elementname. So we check if the original qs filter was looking at the raw // value if it was then we want to filter on the key and not the label if (!array_key_exists($key, JRequest::get('get'))) { $key = "`{$joinTableName}`.`id`"; $this->encryptFieldName($key); return "{$key} {$condition} {$value}"; } } if ($type == 'advanced') { $key = "`{$joinTableName}`.`id`"; $this->encryptFieldName($key); return "{$key} {$condition} {$value}"; } $params =& $this->getParams(); if ($type != 'prefilter') { switch ($element->filter_type) { case 'range': case 'dropdown': $tabletype = 'id'; break; case 'field': default: $tabletype = $params->get('my_table_data', 'username'); break; } $k = '`' . $joinTableName . '`.`' . $tabletype . '`'; } else { if ($this->_rawFilter) { $k = '`' . $joinTableName . '`.`id`'; } else { $tabletype = $params->get('my_table_data', 'username'); $k = '`' . $joinTableName . '`.`' . $tabletype . '`'; } } $this->encryptFieldName($k); $str = "{$k} {$condition} {$value}"; return $str; }