/** * Clean data method * * @param array $data */ public function _cleanData($data = null) { if (empty($data['WebpageMenu']['code']) && !empty($data['WebpageMenu']['name'])) { $data['WebpageMenu']['code'] = ZuhaInflector::asciify($data['WebpageMenu']['name']); } return $data; }
/** * Write link permissions method * */ protected function _writeLinkPermissions() { $acos = array(); $privileges = $this->find('all', array('conditions' => array('Privilege._create' => 1, 'Privilege._read' => 1, 'Privilege._update' => 1, 'Privilege._delete' => 1))); foreach ($privileges as $privilege) { if (!empty($acos[$privilege['Privilege']['aco_id']])) { $acos[$privilege['Privilege']['aco_id']] = $acos[$privilege['Privilege']['aco_id']] . ',' . $privilege['Privilege']['aro_id']; } else { $acos[$privilege['Privilege']['aco_id']] = $privilege['Privilege']['aro_id']; } } $settings = ''; foreach ($acos as $aco => $aros) { $path = $this->Section->getPath($aco); // all of the acos parents if ($path === null) { // if path is null we need to delete the aros_acos that use that aco because it doesn't exist $this->deleteAll(array('Privilege.aco_id' => $aco)); } else { $url = str_replace('controllers', '', Inflector::singularize(Inflector::tableize(ZuhaInflector::flatten(Set::extract('/Section/alias', $path), array('separator' => '/'))))); $settings .= $url . ' = ' . $aros . PHP_EOL; } } App::uses('Setting', 'Model'); $Setting = new Setting(); $data['Setting']['type'] = 'APP'; $data['Setting']['name'] = 'LINK_PERMISSIONS'; $data['Setting']['value'] = trim($settings); $Setting->add($data); }
/** * afterFind callback * * if beforeFind doesn't get the alias, then we need to get it here and add it in * * @param object $Model * @param mixed $results */ public function afterFind(Model $Model, $results, $primary = false) { // look up the alias if it isn't set already if (!empty($results[0][$Model->alias]) && !isset($results[0]['Alias'])) { for ($i = 0, $count = count($results); $i < $count; ++$i) { $alias = $Model->Alias->find('first', array('conditions' => array('Alias.value' => $results[$i][$Model->name]['id'], 'Alias.controller' => Inflector::tableize($Model->name)))); if (!empty($alias)) { $results[$i]['Alias'] = $alias['Alias']; } } } // map the alias to a virtual field for ($i = 0, $count = count($results); $i < $count; ++$i) { if (!empty($results[$i]['Alias'])) { $results[$i][$Model->alias]['_alias'] = '/' . $results[$i]['Alias']['name']; // not dead set on adding the slash } else { $results[$i][$Model->alias]['_alias'] = '/' . strtolower(ZuhaInflector::pluginize($Model->name)) . '/' . Inflector::tableize($Model->name) . '/view/' . $results[$i][$Model->alias]['id']; } } return $results; }
/** * Get Alias method * Finds existing alias and returns it if it exists (else returns a url ready string) * * @param mixed $name * @return array * @todo $name could also be an array in some future case I'm imagining */ public function getAlias($name = null) { $alias = $this->find('first', array('conditions' => array('Alias.name' => ZuhaInflector::urlify($name)))); if (!empty($alias)) { return array('old' => $alias['Alias']['name']); } else { return array('new' => ZuhaInflector::urlify($name)); } }
/** * This Builds the tokens that can be replaced in a string. * @param unknown $models * @return multitype: */ public function buildTokens($models = array(), $assoc = false) { foreach ($models as $model) { App::uses($model, ZuhaInflector::pluginize($model) . '.Model'); $Model = new $model(); $this->tokens[$Model->name] = array_keys($Model->schema()); if ($assoc) { $associated = $Model->listAssociatedModels(); foreach ($associated as $assocModel) { $this->tokens[$assocModel] = array_keys($Model->{$assocModel}->schema()); } } } return $this->tokens; }
/** * Import * * Note: To avoid having to tweak the contents of $csvData, * you should use your db field names as the heading names. * eg: User.id, User.title, User.description * * @param array $data * @return type * @todo Make sure fopen can't be hacked, it's the main point of entry for the base64 attack. */ function importFromCsv($data = array(), $options = array()) { $options = array_merge(array($this->alias => array('notify' => true)), $options); $this->caller = 'import'; if ($data['Import']['csv']['error'] !== UPLOAD_ERR_OK) { return array('errors' => 'We did not receive your file. Please try again.'); } // open the file $handle = fopen($data['Import']['csv']['tmp_name'], "r"); // read the 1st row as headings $header = fgetcsv($handle); // create a message container $return = array('messages' => array(), 'errors' => array()); // read each data row in the file while (($row = fgetcsv($handle)) !== FALSE) { $i++; $csvData['User'] = $data['User']; // for each header field foreach ($header as $k => $head) { // get the data field from Model.field if (strpos($head, '.') !== false) { $h = explode('.', $head); $csvData[$h[0]][$h[1]] = isset($row[$k]) ? $row[$k] : ''; } else { $csvData[$this->alias][$head] = isset($row[$k]) ? $row[$k] : ''; } } // see if we have an id $id = isset($csvData[$this->alias]['id']) ? $csvData[$this->alias]['id'] : 0; // we have an id, so we update if ($id) { // there is 2 options here, // option 1: // load the current row, and merge it with the new data //$this->recursive = -1; //$event = $this->read(null,$id); //$csvData['Event'] = array_merge($event['Event'],$csvData['Event']); // option 2: // set the model id $this->id = $id; } else { // or create a new record $this->create(); } // save the row if ($this->procreate($csvData)) { // success message! $return['messages'][] = __('User for Row %d was saved.', $i); } else { $return['errors'][] = ZuhaInflector::flatten($this->validationErrors); $return['messages'][] = __('User for Row %d failed to save.', $i); } } // close the file fclose($handle); // return the messages return $return; }
/** * Tables * * A list of all tables, as keys with their corresponding plugin as values * * @access public * @return array */ public function _tables() { $db = ConnectionManager::getDataSource('default'); foreach ($db->listSources() as $table) { if (strpos($table, 'zbk_') === false) { $plugin = ZuhaInflector::pluginize($table); if (ctype_lower($plugin)) { throw new Exception(__('I bet someone added a db table (%s), without noting it in bootstrap::ZuhaInflector::pluginize. Please check.', $table)); } $tables[$table] = $plugin; } } return $tables; }
/** * String to Url * Converts the given string to a no spaces, no special characters, no cases string, like a url. * Unlike the asciify function it changes + (plus signs) to / (slashes) * * Tänk efter nu – förr'n vi föser dig b+ort BECOMES tank-efter-nu-forrn-vi-foser-dig-b/ort * * Usage : ZuhaInflector::urlify('some string'); * * @param string $str * @param array $replace * @param string $delimiter * @return string */ public static function urlify($str, $delimiter = '-') { $strs = explode('+', $str); $string = ''; for ($i = 0; $i < count($strs); $i++) { $parts[] = ZuhaInflector::asciify(trim($strs[$i])); } return implode('/', $parts); }
/** * Procreate method * * @param uuid $userRoleId */ public function procreate($userRoleId = null) { if ($this->request->is('post')) { $this->User->autoLogin = false; if ($this->User->procreate($this->request->data)) { $this->Session->setFlash(__('User created.')); $this->redirect(array('action' => 'dashboard')); } else { $this->Session->setFlash(__('Error, user save failed ' . ZuhaInflector::flatten($this->User->invalidFields()))); } } $userRoles = $this->User->UserRole->find('list', array('conditions' => array('UserRole.id !=' => 1, 'UserRole.name !=' => 'guests'))); // remove the administrators group by default - too insecure $userRoleId = count($userRoles) == 1 && empty($userRoleId) ? key($userRoles) : $userRoleId; $userRoleId = defined('__APP_DEFAULT_USER_REGISTRATION_ROLE_ID') && empty($userRoleId) ? __APP_DEFAULT_USER_REGISTRATION_ROLE_ID : $userRoleId; $this->set(compact('userRoleId', 'userRoles')); $title = !empty($userRoles[$userRoleId]) ? Inflector::humanize($userRoles[$userRoleId]) . ' Registration' : 'User Registration'; $this->set('title_for_layout', $title . ' | ' . __SYSTEM_SITE_NAME); $this->set('page_title_for_layout', $title); }
/** * Sitemap method * Write the sitemap to the webroot folder */ public function writeSitemap() { App::uses('Folder', 'Utility'); App::uses('File', 'Utility'); $sitemap = array(); $models = App::objects($plugin . '.Model'); $plugins = CakePlugin::loaded(); foreach ($plugins as $plugin) { // the else here was App::objects($pluginPath . '.Model') // not totally sure the changing to just plugin, won't break something $models = !empty($models) ? array_merge($models, App::objects($plugin . '.Model')) : App::objects($plugin . '.Model'); } sort($models); foreach ($models as $model) { strpos($model, 'AppModel') || strpos($model, 'AppModel') === 0 ? null : ($return[$model] = $model); } foreach (array_reverse($return) as $key => $model) { $model = ZuhaInflector::pluginize($model) ? ZuhaInflector::pluginize($model) . '.' . $model : $model; try { $Model = ClassRegistry::init($model); } catch (Exception $e) { $Model = false; // ignore, we don't care about missing plugin exceptions here // debug($e->getMessage()); } if (method_exists($Model, 'sitemap') && is_callable(array($Model, 'sitemap'))) { $map = $Model->sitemap(); $sitemap = is_array($map) ? array_merge($sitemap, $map) : $sitemap; } } // let's output the actual file here $path = ROOT . DS . SITE_DIR . DS . 'Locale' . DS . 'View' . DS . 'webroot'; $dir = new Folder($path); $file = new File($dir->pwd() . DS . 'sitemap.xml'); $content = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . PHP_EOL; foreach ($sitemap as $page) { $content .= "\t<url>" . PHP_EOL . "\t\t"; $content .= '<loc>' . $page['url']['loc'] . '</loc>' . PHP_EOL . "\t\t"; $content .= '<lastmod>' . $page['url']['lastmod'] . '</lastmod>' . PHP_EOL . "\t\t"; $content .= '<changefreq>' . $page['url']['changefreq'] . '</changefreq>' . PHP_EOL . "\t\t"; $content .= '<priority>' . $page['url']['priority'] . '</priority>' . PHP_EOL . "\t"; $content .= '</url>' . PHP_EOL; } $content .= '</urlset>'; if ($file->write($content)) { $file->close(); return true; } else { return false; } }
public function addRecursiveData($model, $data) { $Model = ClassRegistry::init(ZuhaInflector::pluginize($model) . '.' . $model); $Model->recursive = 1; $data = $Model->find('first', array('conditions' => array("{$Model->name}.id" => $data[$Model->name]['id']))); return $data; }
/** * Protected add method * * If a gallery id is given, check the defaults, attach the upload behavior, and perform the upload. * If no gallery id is given, create a gallery first using site settings, and make the submitted image the th * The gallery add() function calls back to this function to perform the upload. * * This protected version of the add function was pushed down so that it could be called multiple times. * * @access protected * @param array * @param string * @return bool */ protected function _add($data, $uploadFieldName) { $data = $this->checkForGallery($data); if (!empty($data['GalleryImage']['gallery_id'])) { if ($data['GalleryImage']['mimetype'] == 'video') { // special "video" keyword case where we just save the image data because its a video return $this->save($data); } else { if (!empty($data['GalleryImage'][$uploadFieldName])) { // existing gallery and image submitted $uploadOptions[$uploadFieldName] = $this->_getImageOptions($data); $this->Behaviors->attach('Galleries.MeioUpload', $uploadOptions); $this->create(); if ($this->save($data)) { return true; } else { throw new Exception(__('ERROR : %s', ZuhaInflector::flatten($this->invalidFields()))); } } else { // just saving an existing gallery if ($this->Gallery->save($data)) { return true; } else { throw new Exception(__d('galleries', 'ERROR : Gallery save failed.', true)); } } } } else { // new gallery if ($this->Gallery->add($data, $uploadFieldName)) { return true; } else { throw new Exception(__d('galleries', 'ERROR : Gallery add failed.', true)); } } }
/** * Clean data method * * @param array $data * @return array $data */ protected function _cleanData($data) { // handle if we are saving a page automatically and only have the alias if (!empty($data['Alias']['name']) && empty($data['WebpageMenuItem']['item_url'])) { $data['WebpageMenuItem']['item_url'] = '/' . $data['Alias']['name']; } // handle beforeSave() type data if (empty($data['WebpageMenuItem']['parent_id']) && !empty($data['WebpageMenuItem']['menu_id'])) { $data['WebpageMenuItem']['parent_id'] = $data['WebpageMenuItem']['menu_id']; } // handle save() type data if (empty($data['parent_id']) && !empty($data['menu_id'])) { $data['parent_id'] = $data['menu_id']; } // handle beforeSave() type data if (empty($data['WebpageMenuItem']['name']) && !empty($data['WebpageMenuItem']['item_text'])) { $data['WebpageMenuItem']['name'] = $data['WebpageMenuItem']['item_text']; } // handle save() type data if (empty($data['name']) && !empty($data['item_text'])) { $data['name'] = $data['item_text']; } // put data in, to create a check data for whether to create page or not() // it is in the cleanData function because we add some data to the save depending on creation of a page // make sure this gets fired last after all other $data updates if (!empty($data['WebpageMenuItem']['item_url']) && strpos($data['WebpageMenuItem']['item_url'], 'http') !== 0) { // if link_url starts with http do nothing } elseif ($data['WebpageMenuItem']['page_type'] == 'content' || $data['WebpageMenuItem']['page_type'] == 'section' || $data['WebpageMenuItem']['page_type'] == 'plugin') { // NOTE : don't change this if above, if you do installing a new site fails App::uses('Alias', 'Model'); $Alias = new Alias(); // else see if the page already exists $url = strpos($data['WebpageMenuItem']['item_url'], '/') === 0 ? substr($data['WebpageMenuItem']['item_url'], 1) : $data['WebpageMenuItem']['item_url']; $urlAlias = $Alias->getAlias($url); $textAlias = $Alias->getAlias($data['WebpageMenuItem']['item_text']); if (!empty($urlAlias['old']) || !empty($textAlias['old'])) { // if it does we don't need create a page, just move on ignoring the rest $data['WebpageMenuItem']['item_url'] = !empty($data['WebpageMenuItem']['item_url']) ? $data['WebpageMenuItem']['item_url'] : '/' . $textAlias['old']; } elseif ($data['WebpageMenuItem']['page_type'] == 'content' || $data['WebpageMenuItem']['page_type'] == 'section') { // if not then create page (depending on page type) $this->set($data); if ($this->validates()) { // map menu data to webpage data $webpage['Alias']['name'] = empty($data['WebpageMenuItem']['item_url']) ? $Alias->getNewAlias($data['WebpageMenuItem']['item_text']) : null; // if link_url is blank, set the link_url from the name (asciifyy) $webpage['Webpage']['name'] = $data['WebpageMenuItem']['item_text']; $webpage['Webpage']['title'] = $data['WebpageMenuItem']['item_text']; App::uses('Webpage', 'Webpages.Model'); $Webpage = new Webpage(); $webpage = $Webpage->placeholder($webpage, array('create' => true, 'type' => $data['WebpageMenuItem']['page_type'])); unset($webpage['Webpage']); // don't want returned data to save again unset($webpage['Child']); // don't want returned data to save again unset($webpage['Alias']); // don't want returned data to save again $data = Set::merge($data, $webpage); } else { // it isn't going to save anyway, it didn't validate so do nothing, data should be resubmitted } } elseif ($data['WebpageMenuItem']['page_type'] == 'plugin') { $plugin = ZuhaInflector::pluginize($data['WebpageMenuItem']['item_text']); App::uses($plugin . 'AppModel', $plugin . '.Model'); $className = $plugin . 'AppModel'; $Model = new $className(); if (method_exists($Model, 'menuInit')) { // see if the plugin model has a function to generate starting links (note : handle test data in the schema) $data = $Model->menuInit($data); } else { throw new Exception('Create the menuInit() method in the ' . $plugin . 'AppModel file.'); } } } if (!empty($data['WebpageMenuItem']['parent_id']) && empty($data['WebpageMenuItem']['user_role_id'])) { $data['WebpageMenuItem']['user_role_id'] = $this->field('user_role_id', array($this->alias . '.id' => $data['WebpageMenuItem']['parent_id'])); } if (!empty($data['ChildMenuItem'][0])) { for ($i = 0; $i < count($data['ChildMenuItem']); ++$i) { if (empty($data['ChildMenuItem'][$i]['user_role_id']) && !empty($data['WebpageMenuItem']['user_role_id'])) { $data['ChildMenuItem'][$i]['user_role_id'] = $data['WebpageMenuItem']['user_role_id']; } } } return $data; }
/** * Upload method * * @param object $Model * @param array $data */ public function upload(Model $Model, $data) { $data = !empty($data) ? $data : $this->data; if (!empty($data['File'])) { ini_set('memory_limit', '750M'); foreach ($data['File'] as $attachment) { if (!empty($attachment['file']['tmp_name'])) { // make sure there is actually a file to upload $data[$this->ImageStorage->alias]['adapter'] = 'S3Storage'; $model = $this->_detectModelByFileType($attachment['file']['type']); if ($model) { $data['File']['model'] = $model; $data['File']['adapter'] = 'S3Storage'; App::uses('File', 'Utility'); $file = new File($attachment['file']['tmp_name']); $info = $file->info(); // fill in empty data that should have something (if possible) $attachment['user_id'] = !empty($attachment['user_id']) ? $attachment['user_id'] : CakeSession::read('Auth.User.id'); $attachment['title'] = !empty($attachment['title']) ? $attachment['title'] : $attachment['file']['name']; $attachment['alt'] = !empty($attachment['alt']) ? $attachment['alt'] : ZuhaInflector::asciify($attachment['file']['name']); $saveData = array($this->{$model}->alias => array_merge($attachment, array('filename' => uniqid('', true) . '.' . substr(strrchr($attachment['file']['name'], '.'), 1), 'filesize' => $info['filesize'], 'file' => $attachment['file'], 'mime_type' => $info['mime'], 'extension' => substr(strrchr($attachment['file']['name'], '.'), 1), 'adapter' => 'S3Storage'))); $saveData[$this->{$model}->alias]['file']['name'] = uniqid('', true) . '.' . substr(strrchr($attachment['file']['name'], '.'), 1); $saveData['FileAttach'] = array_merge($attachment, array('model' => $Model->name, 'foreign_key' => $Model->id)); try { $this->{$model}->create(); if ($this->{$model}->save($saveData)) { $saveData['FileAttach']['file_storage_id'] = $this->{$model}->getLastInsertID(); $this->FileAttach->create(); $this->FileAttach->save($saveData); } } catch (Exception $e) { debug('Please report this error, with the information below.'); debug($e->getMessage()); debug($this->{$model}->invalidFields()); exit; } } } } } return true; }
/** * Model User Fields * * checks a model for which relationships are with the user model * @param array $sections */ protected function _modelUserFields($sections) { foreach ($sections as $k => $parent) { $modelName = Inflector::classify($parent['Section']['alias']); $plugin = ZuhaInflector::pluginize($modelName); if (in_array($plugin, CakePlugin::loaded())) { $register = !empty($plugin) ? $plugin . '.' . $modelName : $modelName; if ($Model = ClassRegistry::init($register, true)) { $belongs = $Model->belongsTo; foreach ($belongs as $b) { if ($b['className'] == 'Users.User') { $sections[$k]['userFields'][] = $b['foreignKey']; } } } } } return $sections; }