Type hinting -- start
Inheritance: extends Model, implements JTableInterface
Exemple #1
0
 public function onAfterConstruct(DataModel &$model)
 {
     // This only applies to the front-end
     if (!$model->getContainer()->platform->isFrontend()) {
         return;
     }
     // Get the page parameters
     /** @var \JRegistry $params */
     $params = \JFactory::getApplication()->getPageParameters();
     // Extract the page parameter keys
     $asArray = $params->toArray();
     if (empty($asArray)) {
         // There are no keys; no point in going on.
         return;
     }
     $keys = array_keys($asArray);
     unset($asArray);
     // Loop all page parameter keys
     foreach ($keys as $key) {
         // This is the current model state
         $currentState = $model->getState($key);
         // This is the explicitly requested state in the input
         $explicitInput = $model->input->get($key, null, 'raw');
         // If the current state is empty and there's no explicit input we'll use the page parameters instead
         if (is_null($currentState) && is_null($explicitInput)) {
             $model->setState($key, $params->get($key));
         }
     }
 }
Exemple #2
0
 /**
  * Replace string with tags that reference fields
  *
  * @param   string  $text  Text to process
  *
  * @return  string         Text with tags replace
  */
 protected function parseFieldTags($text)
 {
     $ret = $text;
     // Replace [ITEM:ID] in the URL with the item's key value (usually:
     // the auto-incrementing numeric ID)
     $keyfield = $this->item->getKeyName();
     $replace = $this->item->{$keyfield};
     $ret = str_replace('[ITEM:ID]', $replace, $ret);
     // Replace the [ITEMID] in the URL with the current Itemid parameter
     $ret = str_replace('[ITEMID]', $this->form->getContainer()->input->getInt('Itemid', 0), $ret);
     // Replace other field variables in the URL
     $fields = $this->item->getTableFields();
     foreach ($fields as $fielddata) {
         $fieldname = $fielddata->Field;
         if (empty($fieldname)) {
             $fieldname = $fielddata->column_name;
         }
         $search = '[ITEM:' . strtoupper($fieldname) . ']';
         $replace = $this->item->{$fieldname};
         if (!is_string($replace)) {
             continue;
         }
         $ret = str_replace($search, $replace, $ret);
     }
     return $ret;
 }
Exemple #3
0
 public function check()
 {
     if (empty($this->published)) {
         $this->published = 0;
     }
     return parent::check();
 }
Exemple #4
0
 public function __construct(Container $container, array $config = array())
 {
     // I have to manually disable autoChecks, otherwise FOF will try to search for the form, raising
     // a fatal error
     $config['autoChecks'] = false;
     parent::__construct($container, $config);
 }
Exemple #5
0
 /**
  * Get the rendering of this field type for a repeatable (grid) display,
  * e.g. in a view listing many item (typically a "browse" task)
  *
  * @since 2.0
  *
  * @return  string  The field HTML
  *
  * @throws  DataModelRequired
  */
 public function getRepeatable()
 {
     if (!$this->item instanceof DataModel) {
         throw new DataModelRequired(__CLASS__);
     }
     $config = $this->getConfig();
     $html = '<div class="btn-group">';
     // Render a published field
     if ($this->item->hasField('enabled')) {
         $publishedFieldName = $this->item->getFieldAlias('enabled');
         if ($config['published'] || $config['unpublished']) {
             // Generate a FieldInterfacePublished field
             $publishedField = $this->getPublishedField($publishedFieldName);
             // Render the publish button
             $html .= $publishedField->getRepeatable();
         }
         if ($config['archived']) {
             $archived = $this->item->getFieldValue($publishedFieldName) == 2 ? true : false;
             // Create dropdown items
             $action = $archived ? 'unarchive' : 'archive';
             JHtml::_('actionsdropdown.' . $action, 'cb' . $this->rowid);
         }
         if ($config['trash']) {
             $trashed = $this->item->getFieldValue($publishedFieldName) == -2 ? true : false;
             $action = $trashed ? 'untrash' : 'trash';
             JHtml::_('actionsdropdown.' . $action, 'cb' . $this->rowid);
         }
         // Render dropdown list
         if ($config['archived'] || $config['trash']) {
             $html .= JHtml::_('actionsdropdown.render', $this->item->title);
         }
     }
     $html .= '</div>';
     return $html;
 }
Exemple #6
0
 /**
  * Replace string with tags that reference fields
  *
  * @param   string  $text  Text to process
  *
  * @return  string         Text with tags replace
  */
 protected function parseFieldTags($text)
 {
     $ret = $text;
     // Replace [ITEM:ID] in the URL with the item's key value (usually:
     // the auto-incrementing numeric ID)
     if (is_null($this->item)) {
         $this->item = $this->form->getModel();
     }
     $replace = $this->item->getId();
     $ret = str_replace('[ITEM:ID]', $replace, $ret);
     // Replace the [ITEMID] in the URL with the current Itemid parameter
     $ret = str_replace('[ITEMID]', $this->form->getContainer()->input->getInt('Itemid', 0), $ret);
     // Replace the [TOKEN] in the URL with the Joomla! form token
     $ret = str_replace('[TOKEN]', \JFactory::getSession()->getFormToken(), $ret);
     // Replace other field variables in the URL
     $data = $this->item->getData();
     foreach ($data as $field => $value) {
         // Skip non-processable values
         if (is_array($value) || is_object($value)) {
             continue;
         }
         $search = '[ITEM:' . strtoupper($field) . ']';
         $ret = str_replace($search, $value, $ret);
     }
     return $ret;
 }
Exemple #7
0
 /**
  * Publish or unpublish a DataModel item based on its publish_up / publish_down fields
  *
  * @param   DataModel  $row  The DataModel to publish/unpublish
  *
  * @return  void
  */
 protected function publishByDate(DataModel $row)
 {
     static $uNow = null;
     \JLoader::import('joomla.utilities.date');
     if (is_null($uNow)) {
         $jNow = new \JDate();
         $uNow = $jNow->toUnix();
     }
     $db = $this->container->db;
     $triggered = false;
     if ($row->publish_down && $row->publish_down != $db->getNullDate()) {
         $publish_down = $this->normaliseDate($row->publish_down, '2038-01-18 00:00:00');
         $publish_up = $this->normaliseDate($row->publish_up, '2001-01-01 00:00:00');
         $jDown = new \JDate($publish_down);
         $jUp = new \JDate($publish_up);
         if ($uNow >= $jDown->toUnix() && $row->enabled) {
             $row->enabled = 0;
             $triggered = true;
         } elseif ($uNow >= $jUp->toUnix() && !$row->enabled && $uNow < $jDown->toUnix()) {
             $row->enabled = 1;
             $triggered = true;
         }
     }
     if ($triggered) {
         $row->save();
     }
 }
Exemple #8
0
 /**
  * Builds the query for the ordering list.
  *
  * @since 2.3.2
  *
  * @return \JDatabaseQuery  The query for the ordering form field
  */
 protected function getQuery()
 {
     $ordering = $this->name;
     $title = $this->element['ordertitle'] ? (string) $this->element['ordertitle'] : $this->item->getFieldAlias('title');
     $db = $this->form->getContainer()->platform->getDbo();
     $query = $db->getQuery(true);
     $query->select(array($db->quoteName($ordering, 'value'), $db->quoteName($title, 'text')))->from($db->quoteName($this->item->getTableName()))->order($ordering);
     return $query;
 }
Exemple #9
0
 /**
  * Public constructor. Overrides the parent constructor.
  *
  * @see DataModel::__construct()
  *
  * @param   Container  $container  The configuration variables to this model
  * @param   array      $config     Configuration values for this model
  *
  * @throws \FOF30\Model\DataModel\Exception\NoTableColumns
  */
 public function __construct(Container $container, array $config = array())
 {
     $config['tableName'] = '#__ars_environments';
     $config['idFieldName'] = 'id';
     parent::__construct($container, $config);
     $this->blacklistFilters(['title']);
     // Behaviours
     $this->addBehaviour('Filters');
 }
Exemple #10
0
 public function __call($method, $args)
 {
     if (isset($this->methods[$method])) {
         $func = $this->methods[$method];
         // Let's pass an instance of ourself, so we can manipulate other closures
         array_unshift($args, $this);
         return call_user_func_array($func, $args);
     }
     return parent::__call($method, $args);
 }
Exemple #11
0
 public function __construct(Container $container, array $config)
 {
     $defaultConfig = ['tableName' => '#__ak_profiles', 'idFieldName' => 'id'];
     if (!is_array($config) || empty($config)) {
         $config = [];
     }
     $config = array_merge($defaultConfig, $config);
     parent::__construct($container, $config);
     $this->addBehaviour('filters');
     $this->blacklistFilters(['configuration', 'filters']);
 }
Exemple #12
0
 /**
  * Public constructor. Initialises the relation.
  *
  * @param   DataModel $parentModel       The data model we are attached to
  * @param   string    $foreignModelName  The name of the foreign key's model in the format "modelName@com_something"
  * @param   string    $localKey          The local table key for this relation
  * @param   string    $foreignKey        The foreign key for this relation
  * @param   string    $pivotTable        For many-to-many relations, the pivot (glue) table
  * @param   string    $pivotLocalKey     For many-to-many relations, the pivot table's column storing the local key
  * @param   string    $pivotForeignKey   For many-to-many relations, the pivot table's column storing the foreign key
  */
 public function __construct(DataModel $parentModel, $foreignModelName, $localKey = null, $foreignKey = null, $pivotTable = null, $pivotLocalKey = null, $pivotForeignKey = null)
 {
     $this->parentModel = $parentModel;
     $this->foreignModelClass = $foreignModelName;
     $this->localKey = $localKey;
     $this->foreignKey = $foreignKey;
     $this->pivotTable = $pivotTable;
     $this->pivotLocalKey = $pivotLocalKey;
     $this->pivotForeignKey = $pivotForeignKey;
     $this->container = $parentModel->getContainer();
     $class = $foreignModelName;
     if (strpos($class, '@') === false) {
         $this->foreignModelComponent = null;
         $this->foreignModelName = $class;
     } else {
         $foreignParts = explode('@', $class, 2);
         $this->foreignModelComponent = $foreignParts[1];
         $this->foreignModelName = $foreignParts[0];
     }
 }
Exemple #13
0
 /**
  * Applies the relation filters to the foreign model when getData is called
  *
  * @param DataModel  $foreignModel   The foreign model you're operating on
  * @param DataModel\Collection $dataCollection If it's an eager loaded relation, the collection of loaded parent records
  *
  * @return boolean Return false to force an empty data collection
  */
 protected function filterForeignModel(DataModel $foreignModel, DataModel\Collection $dataCollection = null)
 {
     // Decide how to proceed, based on eager or lazy loading
     if (is_object($dataCollection)) {
         // Eager loaded relation
         if (!empty($dataCollection)) {
             // Get a list of local keys from the collection
             $values = array();
             /** @var $item DataModel */
             foreach ($dataCollection as $item) {
                 $v = $item->getFieldValue($this->localKey, null);
                 if (!is_null($v)) {
                     $values[] = $v;
                 }
             }
             // Keep only unique values
             $values = array_unique($values);
             // Apply the filter
             if (!empty($values)) {
                 $foreignModel->where($this->foreignKey, 'in', $values);
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         // Lazy loaded relation; get the single local key
         $localKey = $this->parentModel->getFieldValue($this->localKey, null);
         if (is_null($localKey)) {
             return false;
         }
         $foreignModel->where($this->foreignKey, '==', $localKey);
     }
     return true;
 }
Exemple #14
0
 /**
  * Get the rendering of this field type for a repeatable (grid) display,
  * e.g. in a view listing many item (typically a "browse" task)
  *
  * @since 2.0
  *
  * @return  string  The field HTML
  *
  * @throws  DataModelRequired
  */
 public function getRepeatable()
 {
     // Should I support checked-out elements?
     $checkoutSupport = false;
     if (isset($this->element['checkout'])) {
         $checkoutSupportValue = (string) $this->element['checkout'];
         $checkoutSupport = in_array(strtolower($checkoutSupportValue), array('yes', 'true', 'on', 1));
     }
     if (!$this->item instanceof DataModel) {
         throw new DataModelRequired(__CLASS__);
     }
     // Is this record checked out?
     $userId = $this->form->getContainer()->platform->getUser()->get('id', 0);
     $checked_out = false;
     if ($checkoutSupport) {
         $checked_out = $this->item->isLocked($userId);
     }
     // Get the key id for this record
     $key_field = $this->item->getKeyName();
     $key_id = $this->item->{$key_field};
     // Get the HTML
     return JHtml::_('grid.id', $this->rowid, $key_id, $checked_out);
 }
Exemple #15
0
 /**
  * Gets the list of IDs from the request data
  *
  * @param DataModel $model      The model where the record will be loaded
  * @param bool      $loadRecord When true, the record matching the *first* ID found will be loaded into $model
  *
  * @return array
  */
 public function getIDsFromRequest(DataModel &$model, $loadRecord = true)
 {
     // Get the ID or list of IDs from the request or the configuration
     $cid = $this->input->get('cid', array(), 'array');
     $id = $this->input->getInt('id', 0);
     $kid = $this->input->getInt($model->getIdFieldName(), 0);
     $ids = array();
     if (is_array($cid) && !empty($cid)) {
         $ids = $cid;
     } else {
         if (empty($id)) {
             if (!empty($kid)) {
                 $ids = array($kid);
             }
         } else {
             $ids = array($id);
         }
     }
     if ($loadRecord && !empty($ids)) {
         $id = reset($ids);
         $model->find(array('id' => $id));
     }
     return $ids;
 }
Exemple #16
0
 public function onBeforeDelete(DataModel &$model, $oid)
 {
     if (!$model->isAssetsTracked()) {
         return true;
     }
     $k = $model->getKeyName();
     // If the table is not loaded, let's try to load it with the id
     if (!$model->{$k}) {
         $model->load($oid);
     }
     // If I have an invalid assetName I have to stop
     $name = $model->getAssetName();
     // Do NOT touch JTable here -- we are loading the core asset table which is a JTable, not a FOF Table
     $asset = \JTable::getInstance('Asset');
     if ($asset->loadByName($name)) {
         // Since we are using JTable, there is no way to mock it and test for failures :(
         // @codeCoverageIgnoreStart
         if (!$asset->delete()) {
             throw new \Exception($asset->getError());
         }
         // @codeCoverageIgnoreEnd
     }
     return true;
 }
Exemple #17
0
 public function check()
 {
     $this->assertNotEmpty($this->release_id, 'ERR_ITEM_NEEDS_CATEGORY');
     // Get some useful info
     $db = $this->getDBO();
     $query = $db->getQuery(true)->select(array($db->qn('title'), $db->qn('alias')))->from($db->qn('#__ars_items'))->where($db->qn('release_id') . ' = ' . $db->q($this->release_id));
     if ($this->id) {
         $query->where('NOT(' . $db->qn('id') . '=' . $db->q($this->id) . ')');
     }
     $db->setQuery($query);
     $info = $db->loadAssocList();
     $titles = array();
     $aliases = array();
     foreach ($info as $infoitem) {
         $titles[] = $infoitem['title'];
         $aliases[] = $infoitem['alias'];
     }
     // Let's get automatic item title/description records
     $subQuery = $db->getQuery(true)->select($db->qn('category_id'))->from($db->qn('#__ars_releases'))->where($db->qn('id') . ' = ' . $db->q($this->release_id));
     $query = $db->getQuery(true)->select('*')->from($db->qn('#__ars_autoitemdesc'))->where($db->qn('category') . ' IN (' . $subQuery . ')')->where('NOT(' . $db->qn('published') . '=' . $db->q(0) . ')');
     $db->setQuery($query);
     $autoitems = $db->loadObjectList();
     $auto = (object) array('title' => '', 'description' => '', 'environments' => '');
     if (!empty($autoitems)) {
         $fname = basename($this->type == 'file' ? $this->filename : $this->url);
         foreach ($autoitems as $autoitem) {
             $pattern = $autoitem->packname;
             if (empty($pattern)) {
                 continue;
             }
             if (fnmatch($pattern, $fname)) {
                 $auto = $autoitem;
                 break;
             }
         }
     }
     // Added environment ID
     if (!empty($this->environments) && is_array($this->environments)) {
         // Filter out empty environments
         $temp = array();
         foreach ($this->environments as $eid) {
             if ($eid) {
                 $temp[] = $eid;
             }
         }
         $this->environments = $temp;
     }
     // Check if a title exists
     if (!$this->title) {
         // No, try the automatic rule-based title
         $this->title = $auto->title;
         if (!$this->title) {
             // No, try to get the filename
             switch ($this->type) {
                 case 'file':
                     if ($this->filename) {
                         $this->title = basename($this->filename);
                     }
                     break;
                 case 'link':
                     if ($this->url) {
                         $this->title = basename($this->url);
                     }
                     break;
             }
             $this->assertNotEmpty($this->title, 'ERR_ITEM_NEEDS_TITLE');
         }
     }
     $this->assertNotInArray($this->title, $titles, 'ERR_ITEM_NEEDS_TITLE_UNIQUE');
     $stripDesc = strip_tags($this->description);
     $stripDesc = trim($stripDesc);
     if (empty($this->description) || empty($stripDesc)) {
         $this->description = $auto->description;
     }
     // If the alias is missing, auto-create a new one
     if (!$this->alias) {
         $source = $this->title;
         switch ($this->type) {
             case 'file':
                 if ($this->filename) {
                     $source = basename($this->filename);
                 }
                 break;
             case 'link':
                 if ($this->url) {
                     $source = basename($this->url);
                 }
                 break;
         }
         $this->alias = str_replace('.', '-', $source);
         // Create a smart alias
         $alias = strtolower($source);
         $alias = str_replace(' ', '-', $alias);
         $alias = str_replace('.', '-', $alias);
         $this->alias = (string) preg_replace('/[^A-Z0-9_-]/i', '', $alias);
     }
     $this->assertNotEmpty($this->alias, 'ERR_ITEM_NEEDS_ALIAS');
     $this->assertNotInArray($this->alias, $aliases, 'ERR_ITEM_NEEDS_ALIAS_UNIQUE');
     $this->assertInArray($this->type, ['link', 'file'], 'ERR_ITEM_NEEDS_TYPE');
     switch ($this->type) {
         case 'file':
             $this->assertNotEmpty($this->filename, 'ERR_ITEM_NEEDS_FILENAME');
             break;
         case 'link':
             $this->assertNotEmpty($this->url, 'ERR_ITEM_NEEDS_LINK');
             break;
     }
     \JLoader::import('joomla.filter.filterinput');
     $filter = \JFilterInput::getInstance(null, null, 1, 1);
     // Filter the description using a safe HTML filter
     if (!empty($this->description)) {
         $this->description = $filter->clean($this->description);
     }
     // Set the access to registered if there are subscription groups defined
     if (!empty($this->groups) && $this->access == 1) {
         $this->access = 2;
     }
     if (is_null($this->published) || $this->published == '') {
         $this->published = 0;
     }
     // Apply an update stream, if possible
     if (empty($this->updatestream)) {
         $db = $this->getDBO();
         $subquery = $db->getQuery(true)->select($db->qn('category_id'))->from('#__ars_releases')->where($db->qn('id') . ' = ' . $db->q($this->release_id));
         $query = $db->getQuery(true)->select('*')->from($db->qn('#__ars_updatestreams'))->where($db->qn('category') . ' IN (' . $subquery . ')');
         $db->setQuery($query);
         $streams = $db->loadObjectList();
         if (!empty($streams)) {
             $fname = basename($this->type == 'file' ? $this->filename : $this->url);
             foreach ($streams as $stream) {
                 $pattern = $stream->packname;
                 $element = $stream->element;
                 if (empty($pattern) && !empty($element)) {
                     $pattern = $element . '*';
                 }
                 if (empty($pattern)) {
                     continue;
                 }
                 if (fnmatch($pattern, $fname)) {
                     $this->updatestream = $stream->id;
                     break;
                 }
             }
         }
     }
     // Check for MD5 and SHA1 existence
     if (empty($this->md5) || empty($this->sha1) || empty($this->filesize)) {
         if ($this->type == 'file') {
             $target = null;
             $folder = null;
             $filename = $this->filename;
             /** @var Releases $releaseModel */
             $releaseModel = $this->container->factory->model('Releases')->tmpInstance();
             /** @var Releases $release */
             $release = $releaseModel->find($this->release_id);
             if ($release->id) {
                 if ($release->category->id) {
                     $folder = $release->category->directory;
                 }
             }
             $url = null;
             if (!empty($folder)) {
                 $potentialPrefix = substr($folder, 0, 5);
                 $potentialPrefix = strtolower($potentialPrefix);
                 if ($potentialPrefix == 's3://') {
                     $check = substr($folder, 5);
                     $s3 = AmazonS3::getInstance();
                     $items = $s3->getBucket('', $check);
                     if (empty($items)) {
                         $folder = null;
                         return false;
                     } else {
                         // Get a signed URL
                         $s3 = Amazons3::getInstance();
                         $url = $s3->getAuthenticatedURL(rtrim(substr($folder, 5), '/') . '/' . ltrim($filename, '/'));
                     }
                 } else {
                     \JLoader::import('joomla.filesystem.folder');
                     if (!\JFolder::exists($folder)) {
                         $folder = JPATH_ROOT . '/' . $folder;
                         if (!\JFolder::exists($folder)) {
                             $folder = null;
                         }
                     }
                     if (!empty($folder)) {
                         $filename = $folder . '/' . $filename;
                     }
                 }
             }
         }
         if (!isset($url)) {
             $url = null;
         }
         if ($this->type == 'link' || !is_null($url)) {
             if (is_null($url)) {
                 $url = $this->url;
             }
             $config = \JFactory::getConfig();
             $target = $config->get('tmp_path') . '/temp.dat';
             if (function_exists('curl_exec')) {
                 // By default, try using cURL
                 $process = curl_init($url);
                 curl_setopt($process, CURLOPT_HEADER, 0);
                 // Pretend we are IE7, so that webservers play nice with us
                 curl_setopt($process, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)');
                 curl_setopt($process, CURLOPT_TIMEOUT, 5);
                 curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
                 curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
                 // The @ sign allows the next line to fail if open_basedir is set or if safe mode is enabled
                 @curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
                 @curl_setopt($process, CURLOPT_MAXREDIRS, 20);
                 $data = curl_exec($process);
                 if ($data !== false) {
                     \JLoader::import('joomla.filesystem.file');
                     $result = \JFile::write($target, $data);
                 }
                 curl_close($process);
             } else {
                 // Use Joomla!'s download helper
                 \JLoader::import('joomla.installer.helper');
                 \JInstallerHelper::downloadPackage($url, $target);
             }
             $filename = $target;
         }
         if (!empty($filename) && is_file($filename)) {
             \JLoader::import('joomla.filesystem.file');
             if (!\JFile::exists($filename)) {
                 $filename = null;
             }
         }
         if (!empty($filename) && is_file($filename)) {
             if (function_exists('hash_file')) {
                 if (empty($this->md5)) {
                     $this->md5 = hash_file('md5', $filename);
                 }
                 if (empty($this->sha1)) {
                     $this->sha1 = hash_file('sha1', $filename);
                 }
             } else {
                 if (function_exists('md5_file') && empty($this->md5)) {
                     $this->md5 = md5_file($filename);
                 }
                 if (function_exists('sha1_file') && empty($this->sha1)) {
                     $this->sha1 = sha1_file($filename);
                 }
             }
             if (empty($this->filesize)) {
                 $filesize = @filesize($filename);
                 if ($filesize !== false) {
                     $this->filesize = $filesize;
                 }
             }
         }
         if (!empty($filename) && is_file($filename) && $this->type == 'link') {
             if (!@unlink($filename)) {
                 \JFile::delete($filename);
             }
         }
     }
     return parent::check();
 }
Exemple #18
0
 /**
  * @param   DataModel  $model
  * @param   \stdClass  $dataObject
  */
 public function onBeforeCreate(&$model, &$dataObject)
 {
     // Handle the created_on field
     if ($model->hasField('created_on')) {
         $nullDate = $model->getDbo()->getNullDate();
         $created_on = $model->getFieldValue('created_on');
         if (empty($created_on) || $created_on == $nullDate) {
             $model->setFieldValue('created_on', $model->getContainer()->platform->getDate()->toSql(false, $model->getDbo()));
             $createdOnField = $model->getFieldAlias('created_on');
             $dataObject->{$createdOnField} = $model->getFieldValue('created_on');
         }
     }
     // Handle the created_by field
     if ($model->hasField('created_by')) {
         $created_by = $model->getFieldValue('created_by');
         if (empty($created_by)) {
             $model->setFieldValue('created_by', $model->getContainer()->platform->getUser()->id);
             $createdByField = $model->getFieldAlias('created_by');
             $dataObject->{$createdByField} = $model->getFieldValue('created_by');
         }
     }
 }
Exemple #19
0
 private function applyModelField(DataModel $model, \SimpleXMLElement &$headerSet, \SimpleXMLElement &$fieldSet, $fieldName, $modelName)
 {
     // This will fail if the model is invalid, e.g. we have example_foobar_id but no #__example_foobars table. The
     // error will balloon up the stack and the field will be rendered as simple numeric field instead of a Model
     // field.
     /** @var DataModel $foreignModel */
     $foreignModel = $model->getContainer()->factory->model($modelName);
     $value_field = $foreignModel->getKeyName();
     if ($foreignModel->hasField('title')) {
         $value_field = $foreignModel->getFieldAlias('title');
     }
     $langDefs = $this->getFieldLabel($fieldName);
     $this->addString($langDefs['label']['key'], $langDefs['label']['value']);
     $this->addString($langDefs['desc']['key'], $langDefs['desc']['value']);
     $header = $headerSet->addChild('header');
     $header->addAttribute('name', $fieldName);
     $header->addAttribute('type', 'Model');
     $header->addAttribute('model', $modelName);
     $header->addAttribute('key_field', $foreignModel->getKeyName());
     $header->addAttribute('value_field', $value_field);
     $header->addAttribute('label', $langDefs['label']['key']);
     $header->addAttribute('sortable', 'true');
     $field = $fieldSet->addChild('field');
     $field->addAttribute('name', $fieldName);
     $field->addAttribute('type', 'Model');
     $field->addAttribute('model', $modelName);
     $field->addAttribute('key_field', $foreignModel->getKeyName());
     $field->addAttribute('value_field', $value_field);
     $field->addAttribute('label', $langDefs['label']['key']);
 }
 public function check()
 {
     $this->assertNotEmpty($this->title, 'COM_ARS_CATEGORY_ERR_NEEDS_TITLE');
     // If the alias is missing, auto-create a new one
     if (!$this->alias) {
         \JLoader::import('joomla.filter.input');
         $alias = str_replace(' ', '-', strtolower($this->title));
         $this->alias = (string) preg_replace('/[^A-Z0-9_-]/i', '', $alias);
     }
     // If no alias could be auto-generated, fail
     $this->assertNotEmpty($this->alias, 'COM_ARS_CATEGORY_ERR_NEEDS_SLUG');
     // Check alias for uniqueness
     $db = $this->getDBO();
     $query = $db->getQuery(true)->select($db->qn('alias'))->from($db->qn('#__ars_categories'));
     if ($this->id) {
         $query->where('NOT(' . $db->qn('id') . ' = ' . $db->q($this->id) . ')');
     }
     $db->setQuery($query);
     $aliases = $db->loadColumn();
     $this->assertNotInArray($this->alias, $aliases, 'COM_ARS_CATEGORY_ERR_NEEDS_UNIQUE_SLUG');
     // Check directory
     \JLoader::import('joomla.filesystem.folder');
     $this->directory = rtrim($this->directory, '/');
     if ($this->directory == 's3:') {
         $this->directory = 's3://';
     }
     $check = trim($this->directory);
     $this->assertNotEmpty($check, 'COM_ARS_CATEGORY_ERR_NEEDS_DIRECTORY');
     $potentialPrefix = substr($check, 0, 5);
     $potentialPrefix = strtolower($potentialPrefix);
     if ($potentialPrefix == 's3://') {
         $check = substr($check, 5);
         if (!empty($check)) {
             $check .= '/';
         }
         $s3 = AmazonS3::getInstance();
         $items = $s3->getBucket('', $check);
         $this->assertNotEmpty($items, 'COM_ARS_CATEGORY_ERR_S3_DIRECTORY_NOT_EXISTS');
     } else {
         if (!\JFolder::exists($this->directory)) {
             $directory = JPATH_SITE . '/' . $this->directory;
             $this->assert(\JFolder::exists($directory), 'COM_ARS_CATEGORY_ERR_DIRECTORY_NOT_EXISTS');
         }
     }
     // Automaticaly fix the type
     if (!in_array($this->type, array('normal', 'bleedingedge'))) {
         $this->type = 'normal';
     }
     // Set the access to registered if there are subscriptions groups defined
     if (empty($this->access)) {
         $this->access = 1;
     }
     if (!empty($this->groups) && $this->access == 1) {
         $this->access = 2;
     }
     if (empty($this->published) && $this->published !== 0) {
         $this->published = 0;
     }
     parent::check();
     return $this;
 }
Exemple #21
0
 /**
  * Renders a Form for an Edit view and returns the corresponding HTML
  *
  * @param   Form   &$form  The form to render
  * @param   DataModel  $model  The model providing our data
  *
  * @return  string    The HTML rendering of the form
  */
 public function renderFormEdit(Form &$form, DataModel $model)
 {
     // Get the key for this model's table
     $key = $model->getKeyName();
     $keyValue = $model->getId();
     $html = '';
     $validate = strtolower($form->getAttribute('validate'));
     if (in_array($validate, array('true', 'yes', '1', 'on'))) {
         \JHTML::_('behavior.formvalidation');
         $class = ' form-validate';
         $this->loadValidationScript($form);
     } else {
         $class = '';
     }
     // Check form enctype. Use enctype="multipart/form-data" to upload binary files in your form.
     $template_form_enctype = $form->getAttribute('enctype');
     if (!empty($template_form_enctype)) {
         $enctype = ' enctype="' . $form->getAttribute('enctype') . '" ';
     } else {
         $enctype = '';
     }
     // Check form name. Use name="yourformname" to modify the name of your form.
     $formname = $form->getAttribute('name');
     if (empty($formname)) {
         $formname = 'adminForm';
     }
     // Check form ID. Use id="yourformname" to modify the id of your form.
     $formid = $form->getAttribute('id');
     if (empty($formid)) {
         $formid = $formname;
     }
     // Check if we have a custom task
     $customTask = $form->getAttribute('customTask');
     if (empty($customTask)) {
         $customTask = '';
     }
     // Get the form action URL
     $platform = $this->container->platform;
     $actionUrl = $platform->isBackend() ? 'index.php' : \JUri::root() . 'index.php';
     $itemid = $this->container->input->getCmd('Itemid', 0);
     if ($platform->isFrontend() && $itemid != 0) {
         $uri = new \JUri($actionUrl);
         if ($itemid) {
             $uri->setVar('Itemid', $itemid);
         }
         $actionUrl = \JRoute::_($uri->toString());
     }
     $html .= '<form action="' . $actionUrl . '" method="post" name="' . $formname . '" id="' . $formid . '"' . $enctype . ' class="form-horizontal' . $class . '">' . "\n";
     $html .= "\t" . '<input type="hidden" name="option" value="' . $this->container->componentName . '" />' . "\n";
     $html .= "\t" . '<input type="hidden" name="view" value="' . $form->getView()->getName() . '" />' . "\n";
     $html .= "\t" . '<input type="hidden" name="task" value="' . $customTask . '" />' . "\n";
     $html .= "\t" . '<input type="hidden" name="' . $key . '" value="' . $keyValue . '" />' . "\n";
     $html .= "\t" . '<input type="hidden" name="' . \JFactory::getSession()->getFormToken() . '" value="1" />' . "\n";
     $html .= $this->renderFormRaw($form, $model, 'edit');
     $html .= '</form>';
     return $html;
 }
Exemple #22
0
 public function check()
 {
     $this->assertNotEmpty($this->category_id, 'COM_RELEASE_ERR_NEEDS_CATEGORY');
     // Get some useful info
     $db = $this->getDBO();
     $query = $db->getQuery(true)->select(array($db->qn('version'), $db->qn('alias')))->from($db->qn('#__ars_releases'))->where($db->qn('category_id') . ' = ' . $db->q($this->category_id));
     if ($this->id) {
         $query->where('NOT(' . $db->qn('id') . '=' . $db->q($this->id) . ')');
     }
     $db->setQuery($query);
     $info = $db->loadAssocList();
     $versions = array();
     $aliases = array();
     foreach ($info as $infoitem) {
         $versions[] = $infoitem['version'];
         $aliases[] = $infoitem['alias'];
     }
     $this->assertNotEmpty($this->version, 'COM_RELEASE_ERR_NEEDS_VERSION');
     $this->assertNotInArray($this->version, $versions, 'COM_RELEASE_ERR_NEEDS_VERSION_UNIQUE');
     // If the alias is missing, auto-create a new one
     if (!$this->alias) {
         \JLoader::import('joomla.filter.input');
         // Get the category title
         /** @var Categories $catModel */
         $catModel = $this->container->factory->model('Categories')->tmpInstance();
         $catItem = $catModel->find($this->category_id);
         // Create a smart alias
         $alias = strtolower($catItem->alias . '-' . $this->version);
         $alias = str_replace(' ', '-', $alias);
         $alias = str_replace('.', '-', $alias);
         $this->alias = (string) preg_replace('/[^A-Z0-9_-]/i', '', $alias);
     }
     $this->assertNotEmpty($this->alias, 'COM_RELEASE_ERR_NEEDS_ALIAS');
     $this->assertNotInArray($this->alias, $aliases, 'COM_RELEASE_ERR_NEEDS_ALIAS_UNIQUE');
     // Automaticaly fix the maturity
     if (!in_array($this->maturity, array('alpha', 'beta', 'rc', 'stable'))) {
         $this->maturity = 'beta';
     }
     \JLoader::import('joomla.filter.filterinput');
     $filter = \JFilterInput::getInstance(null, null, 1, 1);
     // Filter the description using a safe HTML filter
     if (!empty($this->description)) {
         $this->description = $filter->clean($this->description);
     }
     // Filter the notes using a safe HTML filter
     if (!empty($this->notes)) {
         $this->notes = $filter->clean($this->notes);
     }
     // Set the access to registered if there are subscriptions defined
     if (!empty($this->groups) && $this->access == 1) {
         $this->access = 2;
     }
     if (empty($this->published) && $this->published !== 0) {
         $this->published = 0;
     }
     return parent::check();
 }
Exemple #23
0
 public function __construct(Container $container, array $config = array())
 {
     parent::__construct($container, $config);
     $this->belongsTo('contact', 'Contacts', 'contact_id', 'contactpro_contact_id');
 }
Exemple #24
0
 public function check()
 {
     if ($this->container->platform->isFrontend()) {
         $this->user_id = $this->container->platform->getUser()->id;
     }
     $db = $this->getDbo();
     // Should this be a primary or a secondary DLID?
     if (is_null($this->primary)) {
         // Do I have another primary?
         $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__ars_dlidlabels'))->where($db->qn('user_id') . ' = ' . $db->q($this->user_id))->where($db->qn('primary') . ' = ' . $db->q(1));
         if ($this->ars_dlidlabel_id) {
             $query->where('NOT(' . $db->qn('ars_dlidlabel_id') . ' = ' . $db->q($this->ars_dlidlabel_id) . ')');
         }
         $hasPrimary = $db->setQuery($query)->loadResult();
         $this->primary = $hasPrimary ? 0 : 1;
     }
     if ($this->primary) {
         // You can never disable a primary Download ID
         $this->enabled = 1;
         // The primary Download ID title is fixed
         $this->label = '_MAIN_';
     }
     // Do I need to generate a download ID?
     if (empty($this->dlid)) {
         while (empty($this->dlid)) {
             $this->dlid = md5(\JCrypt::genRandomBytes(64));
             // Do I have another primary?
             $query = $db->getQuery(true)->select('COUNT(*)')->from($db->qn('#__ars_dlidlabels'))->where($db->qn('dlid') . ' = ' . $db->q($this->dlid))->where($db->qn('user_id') . ' = ' . $db->q($this->user_id))->where($db->qn('primary') . ' = ' . $db->q($this->primary));
             if ($this->ars_dlidlabel_id) {
                 $query->where('NOT(' . $db->qn('ars_dlidlabel_id') . ' = ' . $db->q($this->ars_dlidlabel_id) . ')');
             }
             $dlidColission = $db->setQuery($query)->loadResult();
             if ($dlidColission) {
                 $this->dlid = null;
             }
         }
     }
     return parent::check();
 }
Exemple #25
0
 /**
  * Converts a DataModel into data suitable for use with the form. The difference to the Model's getData() method is
  * that we process hasOne and belongsTo relations. This is a recursive function which will be called at most
  * $maxLevel deep. You can set this in the form XML file, in the relation_depth attribute.
  *
  * The $modelsProcessed array which is passed in successive recursions lets us prevent pointless Inception-style
  * recursions, e.g. Model A is related to Model B is related to Model C is related to Model A. You clearly don't
  * care to see a.b.c.a.b in the results. You just want a.b.c. Obviously c is indirectly related to a because that's
  * where you began the recursion anyway.
  *
  * @param   DataModel  $model            The item to dump its contents into an array
  * @param   int        $maxLevel         Maximum nesting level of relations to process. Default: 1.
  * @param   array      $modelsProcessed  Array of the fully qualified model class names already processed.
  *
  * @return  array
  * @throws  DataModel\Relation\Exception\RelationNotFound
  */
 protected function modelToBindSource(DataModel $model, $maxLevel = 1, $modelsProcessed = array())
 {
     $maxLevel--;
     $data = $model->toArray();
     $relations = $model->getRelations()->getRelationNames();
     $relationTypes = $model->getRelations()->getRelationTypes();
     $relationTypes = array_map(function ($x) {
         return ltrim($x, '\\');
     }, $relationTypes);
     $relationTypes = array_flip($relationTypes);
     if (is_array($relations) && count($relations) && $maxLevel >= 0) {
         foreach ($relations as $relationName) {
             $rel = $model->getRelations()->getRelation($relationName);
             $class = get_class($rel);
             if (!isset($relationTypes[$class])) {
                 continue;
             }
             if (!in_array($relationTypes[$class], array('hasOne', 'belongsTo'))) {
                 continue;
             }
             /** @var DataModel $relData */
             $relData = $model->{$relationName};
             if (!$relData instanceof DataModel) {
                 continue;
             }
             $modelType = get_class($relData);
             if (in_array($modelType, $modelsProcessed)) {
                 continue;
             }
             $modelsProcessed[] = $modelType;
             $relDataArray = $this->modelToBindSource($relData, $maxLevel, $modelsProcessed);
             if (!is_array($relDataArray) || empty($relDataArray)) {
                 continue;
             }
             foreach ($relDataArray as $k => $v) {
                 $data[$relationName . '.' . $k] = $v;
             }
         }
     }
     return $data;
 }
Exemple #26
0
 /**
  * Creates a \FOF30\Hal\Document using the provided data
  *
  * @param   mixed|array  $data   The data to put in the document
  * @param   DataModel    $model  The model of this view
  *
  * @return  \FOF30\Hal\Document  A HAL-enabled document
  */
 protected function _createDocumentWithHypermedia($data, $model = null)
 {
     // Create a new HAL document
     if (is_array($data)) {
         $count = count($data);
     } else {
         $count = null;
     }
     if ($count == 1) {
         reset($data);
         $document = new Document(end($data));
     } else {
         $document = new Document($data);
     }
     // Create a self link
     $uri = (string) \JUri::getInstance();
     $uri = $this->_removeURIBase($uri);
     $uri = \JRoute::_($uri);
     $document->addLink('self', new Link($uri));
     // Create relative links in a record list context
     if (is_array($data) && $model instanceof DataModel) {
         if (!isset($this->total)) {
             $this->total = $model->count();
         }
         if (!isset($this->limitStart)) {
             $this->limitStart = $model->getState('limitstart', 0);
         }
         if (!isset($this->limit)) {
             $this->limit = $model->getState('limit', 0);
         }
         $pagination = new \JPagination($this->total, $this->limitStart, $this->limit);
         if ($pagination->pagesTotal > 1) {
             // Try to guess URL parameters and create a prototype URL
             // NOTE: You are better off specialising this method
             $protoUri = $this->_getPrototypeURIForPagination();
             // The "first" link
             $uri = clone $protoUri;
             $uri->setVar('limitstart', 0);
             $uri = \JRoute::_($uri);
             $document->addLink('first', new Link($uri));
             // Do we need a "prev" link?
             if ($pagination->pagesCurrent > 1) {
                 $prevPage = $pagination->pagesCurrent - 1;
                 $limitstart = ($prevPage - 1) * $pagination->limit;
                 $uri = clone $protoUri;
                 $uri->setVar('limitstart', $limitstart);
                 $uri = \JRoute::_($uri);
                 $document->addLink('prev', new Link($uri));
             }
             // Do we need a "next" link?
             if ($pagination->pagesCurrent < $pagination->pagesTotal) {
                 $nextPage = $pagination->pagesCurrent + 1;
                 $limitstart = ($nextPage - 1) * $pagination->limit;
                 $uri = clone $protoUri;
                 $uri->setVar('limitstart', $limitstart);
                 $uri = \JRoute::_($uri);
                 $document->addLink('next', new Link($uri));
             }
             // The "last" link?
             $lastPage = $pagination->pagesTotal;
             $limitstart = ($lastPage - 1) * $pagination->limit;
             $uri = clone $protoUri;
             $uri->setVar('limitstart', $limitstart);
             $uri = \JRoute::_($uri);
             $document->addLink('last', new Link($uri));
         }
     }
     return $document;
 }
 /**
  * Applies the relation filters to the foreign model when getData is called
  *
  * @param DataModel  $foreignModel   The foreign model you're operating on
  * @param DataModel\Collection $dataCollection If it's an eager loaded relation, the collection of loaded parent records
  *
  * @return boolean Return false to force an empty data collection
  */
 protected function filterForeignModel(DataModel $foreignModel, DataModel\Collection $dataCollection = null)
 {
     $db = $this->parentModel->getDbo();
     // Decide how to proceed, based on eager or lazy loading
     if (is_object($dataCollection)) {
         // Eager loaded relation
         if (!empty($dataCollection)) {
             // Get a list of local keys from the collection
             $values = array();
             /** @var $item DataModel */
             foreach ($dataCollection as $item) {
                 $v = $item->getFieldValue($this->localKey, null);
                 if (!is_null($v)) {
                     $values[] = $v;
                 }
             }
             // Keep only unique values
             $values = array_unique($values);
             $values = array_map(function ($x) use(&$db) {
                 return $db->q($x);
             }, $values);
             // Get the foreign keys from the glue table
             $query = $db->getQuery(true)->select(array($db->qn($this->pivotLocalKey), $db->qn($this->pivotForeignKey)))->from($db->qn($this->pivotTable))->where($db->qn($this->pivotLocalKey) . ' IN(' . implode(',', $values) . ')');
             $db->setQuery($query);
             $foreignKeysUnmapped = $db->loadRowList();
             $this->foreignKeyMap = array();
             $foreignKeys = array();
             foreach ($foreignKeysUnmapped as $unmapped) {
                 $local = $unmapped[0];
                 $foreign = $unmapped[1];
                 if (!isset($this->foreignKeyMap[$local])) {
                     $this->foreignKeyMap[$local] = array();
                 }
                 $this->foreignKeyMap[$local][] = $foreign;
                 $foreignKeys[] = $foreign;
             }
             // Keep only unique values. However, the array keys are all screwed up. See below.
             $foreignKeys = array_unique($foreignKeys);
             // This looks stupid, but it's required to reset the array keys. Without it where() below fails.
             $foreignKeys = array_merge($foreignKeys);
             // Apply the filter
             if (!empty($foreignKeys)) {
                 $foreignModel->where($this->foreignKey, 'in', $foreignKeys);
             } else {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         // Lazy loaded relation; get the single local key
         $localKey = $this->parentModel->getFieldValue($this->localKey, null);
         if (is_null($localKey) || $localKey === '') {
             return false;
         }
         $query = $db->getQuery(true)->select($db->qn($this->pivotForeignKey))->from($db->qn($this->pivotTable))->where($db->qn($this->pivotLocalKey) . ' = ' . $db->q($localKey));
         $db->setQuery($query);
         $foreignKeys = $db->loadColumn();
         $this->foreignKeyMap[$localKey] = $foreignKeys;
         // If there are no foreign keys (no foreign items assigned to our item) we return false which then causes
         // the relation to return null, marking the lack of data.
         if (empty($foreignKeys)) {
             return false;
         }
         $foreignModel->where($this->foreignKey, 'in', $this->foreignKeyMap[$localKey]);
     }
     return true;
 }
Exemple #28
0
 /**
  * Overrides the DataModel's buildQuery to allow nested set searches using the provided scopes
  *
  * @param bool $overrideLimits
  *
  * @return \JDatabaseQuery
  */
 public function buildQuery($overrideLimits = false)
 {
     $db = $this->getDbo();
     $query = parent::buildQuery($overrideLimits);
     // Wipe out select and from sections
     $query->clear('select');
     $query->clear('from');
     $query->select($db->qn('node') . '.*')->from($db->qn($this->tableName) . ' AS ' . $db->qn('node'));
     if ($this->treeNestedGet) {
         $query->join('CROSS', $db->qn($this->tableName) . ' AS ' . $db->qn('parent'));
     }
     return $query;
 }
Exemple #29
0
 protected function modelToBindSource(DataModel $model)
 {
     $data = $model->toArray();
     $relations = $model->getRelations()->getRelationNames();
     $relationTypes = $model->getRelations()->getRelationTypes();
     $relationTypes = array_map(function ($x) {
         return ltrim($x, '\\');
     }, $relationTypes);
     $relationTypes = array_flip($relationTypes);
     if (is_array($relations) && count($relations)) {
         foreach ($relations as $relationName) {
             $rel = $model->getRelations()->getRelation($relationName);
             $class = get_class($rel);
             if (!isset($relationTypes[$class])) {
                 continue;
             }
             if ($relationTypes[$class] != 'hasOne') {
                 continue;
             }
             $relData = $model->{$relationName};
             if (!$relData instanceof DataModel) {
                 continue;
             }
             $relDataArray = $relData->toArray();
             if (empty($relDataArray) || !is_array($relDataArray)) {
                 continue;
             }
             foreach ($relDataArray as $k => $v) {
                 $data[$relationName . '.' . $k] = $v;
             }
         }
     }
     return $data;
 }
Exemple #30
0
 public function __construct(Container $container, array $config = array())
 {
     parent::__construct($container, $config);
     $this->hasMany('requests', 'Requests', $this->getKeyName(), 'contact_id');
 }