/** * Update the IWwebbox module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { // Update z_blocs table $c = "UPDATE blocks SET bkey = 'Webbox' WHERE bkey = 'webbox'"; if (!DBUtil::executeSQL($c)) { return false; } //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWwebbox'", '', false, ''); $newVarsNames = Array('url', 'width', 'height', 'scrolls', 'widthunit'); $newVars = Array('url' => 'http://phobos.xtec.cat/intraweb', 'width' => '100', 'height' => '600', 'scrolls' => '1', 'widthunit' => '%'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } return true; }
function mediashare_mediahandlerapi_getMediaHandlers() { $dom = ZLanguage::getModuleDomain('mediashare'); $pntable = pnDBGetTables(); // Get handlers if (!($result = DBUtil::selectFieldArray('mediashare_mediahandlers', 'handler', '', '', true, 'title'))) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('mediahandlerapi.getMediaHandlers', 'Could not load the handlers.'), $dom)); } $handlers = array(); foreach ($result as $title => $handler) { $handlers[] = array('handler' => $handler, 'title' => $title, 'mediaTypes' => array()); } $handlersTable = $pntable['mediashare_mediahandlers']; $handlersColumn = $pntable['mediashare_mediahandlers_column']; // Get media types per handler foreach (array_keys($handlers) as $k) { $handler = DataUtil::formatForStore($handlers[$k]['handler']); $sql = "SELECT {$handlersColumn['mimeType']},\r\n {$handlersColumn['fileType']},\r\n {$handlersColumn['foundMimeType']},\r\n {$handlersColumn['foundFileType']},\r\n\t\t\t\t\t\t\t\t\t\t\t {$handlersColumn['active']},\r\n\t\t\t\t\t\t\t\t\t\t\t {$handlersColumn['id']}\r\n FROM {$handlersTable}\r\n WHERE {$handlersColumn['handler']} = '{$handler}'"; $result = DBUtil::executeSQL($sql); if ($result === false) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('mediahandlerapi.getMediaHandlers', "Could not load the types for the handler '{$handler}'."), $dom)); } $colArray = array('mimeType', 'fileType', 'foundMimeType', 'foundFileType', 'active', 'id'); $handlers[$k]['mediaTypes'] = DBUtil::marshallObjects($result, $colArray); } return $handlers; }
/** * Update the IWbookings module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ function upgrade($oldversion) { //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWbookings'", '', false, ''); $newVarsNames = Array('group', 'weeks', 'month_panel', 'weekends', 'eraseold', 'showcolors', 'NTPtime'); $newVars = Array('group' => '', 'weeks' => '1', 'month_panel' => '0', 'weekends' => '0', 'eraseold' => '1', 'showcolors' => '0', 'NTPtime' => '0'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } return true; }
/** * Get all blocks. * * This function gets all block entries from the database. * * @param 'active_status' filter by active status (0=all, 1=active, 2=inactive). * @param 'blockposition' block position id to filter block selection for. * @param 'inactive' force inclusion of inactive blocks (true overrides active_status to 0, false goes with active_status). * @param 'language' language to filter block selection for. * @param 'module_id' module id to filter block selection for. * * @return array array of items, or false on failure. */ public function getall($args) { // create an empty items array $items = array(); // Security check if (!SecurityUtil::checkPermission('Blocks::', '::', ACCESS_OVERVIEW)) { return $items; } $dbtable = DBUtil::getTables(); $blockstable = $dbtable['blocks']; $blockscolumn = $dbtable['blocks_column']; $sort = isset($args['sort']) && $args['sort'] ? $args['sort'] : ''; $sortdir = isset($args['sortdir']) && $args['sortdir'] ? $args['sortdir'] : 'ASC'; if ($sort) { $sort .= " {$sortdir}"; } else { $sort = 'title'; } // backwards parameter compatability if (isset($args['modid']) && is_numeric($args['modid'])) { $args['module_id'] = $args['modid']; } // initialise the where arguments array $whereargs = array(); // filter by block position if (isset($args['blockposition_id']) && is_numeric($args['blockposition_id']) && $args['blockposition_id']) { $where = "pid = {$args['blockposition_id']}"; $bids = DBUtil::selectFieldArray('block_placements', 'bid', $where); $bidList = $bids ? implode(',', $bids) : -1; $whereargs[] = "{$blockscolumn['bid']} IN ({$bidList})"; } // filter by active block status if (isset($args['inactive']) && $args['inactive']) { $args['active_status'] = 0; } if (isset($args['active_status']) && is_numeric($args['active_status']) && $args['active_status']) { // new logic $whereargs[] = "{$blockscolumn['active']} = " . ($args['active_status'] == 1 ? '1' : '0'); } // filter by module if (isset($args['module_id']) && is_numeric($args['module_id']) && $args['module_id']) { $whereargs[] = "{$blockscolumn['mid']} = '" . DataUtil::formatForStore($args['module_id']) . "'"; } // filter by language if (isset($args['language']) && $args['language']) { $whereargs[] = "{$blockscolumn['language']} = '" . DataUtil::formatForStore($args['language']) . "'"; } // construct the where clause $where = ''; if (!empty($whereargs)) { $where = 'WHERE ' . implode(' AND ', $whereargs); } $permFilter = array(); $permFilter[] = array('component_left' => 'Blocks', 'component_middle' => '', 'component_right' => '', 'instance_left' => 'bkey', 'instance_middle' => 'title', 'instance_right' => 'bid', 'level' => ACCESS_OVERVIEW); $joinInfo = array(); $joinInfo[] = array('join_table' => 'modules', 'join_field' => 'name', 'object_field_name' => 'module_name', 'compare_field_table' => 'mid', 'compare_field_join' => 'id'); return DBUtil::selectExpandedObjectArray('blocks', $joinInfo, $where, $sort, -1, -1, '', $permFilter); }
public function getModalitats() { //Verificar permisos $this->throwForbiddenUnless(SecurityUtil::checkPermission('Llicencies::', '::', ACCESS_READ)); $rs = DBUtil::selectFieldArray('llicencies_modalitat', 'descripcio', '', 'id_mod', false, 'id_mod'); foreach ($rs as $key => &$value) { $value = $key."-".$value; } return $rs; }
/** * Return a random user-id. * * @return The resulting random user-id. */ public static function getUserID() { $fa = DBUtil::selectFieldArray('users', 'uid'); $pos = self::getInteger(0, count($fa)); return $fa[$pos]; }
/** * Retrieve a list of attributes defined in the system. * * @param string $sort The column to sort by (optional) (default='attribute_name'). * * @return the system attributes field array */ public static function getSystemAttributes($sort = 'attribute_name') { $dbtables = DBUtil::getTables(); $table = $dbtables['objectdata_attributes']; $column = $dbtables['objectdata_attributes_column']; // ensure module was successfully loaded if (!$table) { return false; } $atrs = DBUtil::selectFieldArray('objectdata_attributes', 'attribute_name', '', 'attribute_name', true); return $atrs; }
/** * The getVar method gets a module variable. * * If the name parameter is included then method returns the * module variable value. * if the name parameter is ommitted then method returns a multi * dimentional array of the keys and values for the module vars. * * @param string $modname The name of the module or pseudo-module (e.g., 'Users', 'ZConfig', '/EventHandlers'). * @param string $name The name of the variable. * @param boolean $default The value to return if the requested modvar is not set. * * @return string|array If the name parameter is included then method returns * string - module variable value * if the name parameter is ommitted then method returns * array - multi dimentional array of the keys * and values for the module vars. */ public static function getVar($modname, $name = '', $default = false) { // if we don't know the modname then lets assume it is the current // active module if (!isset($modname)) { $modname = self::getName(); } // if we haven't got vars for this module (or pseudo-module) yet then lets get them if (!array_key_exists($modname, self::$modvars)) { // A query out to the database should only be needed if the system is upgrading. Use the installing flag to determine this. if (System::isUpgrading()) { $tables = DBUtil::getTables(); $col = $tables['module_vars_column']; $where = "WHERE {$col['modname']} = '" . DataUtil::formatForStore($modname) . "'"; // The following line is not a mistake. A sort string containing one space is used to disable the default sort for DBUtil::selectFieldArray(). $sort = ' '; $results = DBUtil::selectFieldArray('module_vars', 'value', $where, $sort, false, 'name'); if (is_array($results)) { if (!empty($results)) { foreach ($results as $k => $v) { // ref #2045 vars are being stored with 0/1 unserialised. if (array_key_exists($k, $GLOBALS['ZConfig']['System'])) { self::$modvars[$modname][$k] = $GLOBALS['ZConfig']['System'][$k]; } elseif ($v == '0' || $v == '1') { self::$modvars[$modname][$k] = $v; } else { self::$modvars[$modname][$k] = unserialize($v); } } } } // TODO - There should probably be an exception thrown here if $results === false } else { // Prevent a re-query for the same module in the future, where the module does not define any module variables. self::$modvars[$modname] = array(); } } // if they didn't pass a variable name then return every variable // for the specified module as an associative array. // array('var1' => value1, 'var2' => value2) if (empty($name) && array_key_exists($modname, self::$modvars)) { return self::$modvars[$modname]; } // since they passed a variable name then only return the value for // that variable if (isset(self::$modvars[$modname]) && array_key_exists($name, self::$modvars[$modname])) { return self::$modvars[$modname][$name]; } // we don't know the required module var but we established all known // module vars for this module so the requested one can't exist. // we return the default (which itself defaults to false) return $default; }
/** * Get the IDs of the property registers. * * @param string $modname The module name. * @param string $tablename The tablename for which we wish to get the property for. * * @return array The associative field array of register ids for the specified module. */ public static function getRegisteredModuleCategoriesIds($modname, $tablename) { if (!$modname || !$tablename) { return z_exit(__f("Error! Received invalid specifications '%1$s', '%2$s'.", array($modname, $tablename))); } $wheres = array(); $dbtables = DBUtil::getTables(); $col = $dbtables['categories_registry_column']; $wheres[] = "$col[modname]='" . DataUtil::formatForStore($modname) . "'"; $wheres[] = "$col[table]='" . DataUtil::formatForStore($tablename) . "'"; $where = implode(' AND ', $wheres); $fArr = DBUtil::selectFieldArray('categories_registry', 'id', $where, '', false, 'property'); return $fArr; }
/** * Get all users who have commented on the site so far * * @author Mark West * @return array users who've commented so far */ public function getcommentingusers() { // Security check if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_OVERVIEW)) { return array(); } // Get database columns $tables = DBUtil::getTables(); $columns = $tables['EZComments_column']; $where = "$columns[status] = 0"; $items = DBUtil::selectFieldArray('EZComments', 'uid', $where, '', true); return $items; }
/** * Update the IWagendas module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { // Update z_blocs table $c = "UPDATE blocks SET bkey = 'Calendar' WHERE bkey = 'calendar'"; if (!DBUtil::executeSQL($c)) { return false; } $c = "UPDATE blocks SET bkey = 'Next' WHERE bkey = 'next'"; if (!DBUtil::executeSQL($c)) { return false; } //Array de noms $oldVarsNames = DBUtil::selectFieldArray('module_vars', 'name', "`modname` = 'IWagendas'", '', false, ''); $newVarsNames = Array('inicicurs', 'calendariescolar', 'comentaris', 'festiussempre', 'altresfestius', 'informacions', 'periodes', 'llegenda', 'infos', 'vista', 'colors', 'maxnotes', 'adjuntspersonals', 'caducadies', 'urladjunts', 'msgUsersRespDefault', 'msgUsersDefault', 'allowGCalendar'); $newVars = Array('inicicurs' => date('Y'), 'calendariescolar' => 0, 'comentaris' => '', 'festiussempre' => '', 'altresfestius' => '30', 'informacions' => '1', 'periodes' => '', 'llegenda' => 0, 'infos' => 0, 'vista' => -1, 'colors' => 'DBD4A6|555555|FFCC66|FFFFFF|E1EBFF|669ACC|FFFFFF|FFFFFF|FF8484|FFFFFF|DBD4A6|66FF66|3F6F3E|FFFFCC|BBBBBB|000000', 'maxnotes' => '300', 'adjuntspersonals' => '0', 'caducadies' => '30', 'urladjunts' => 'agendas', 'msgUsersRespDefault' => __('You has been added to a new agenda as moderator. You can access the agenda throught the main menu. <br><br>The administrator'), 'msgUsersDefault' => __('You has been added to a new agenda. You can access the agenda throught the main menu. <br><br>The administrator'), 'allowGCalendar' => '0'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } // Update successful return true; }
/** * Get all months and years with news. Used by archive overview * @author Philipp Niethammer * @return array Array of dates (one per month) */ public function getMonthsWithNews($args) { // Security check if (!SecurityUtil::checkPermission('News::', '::', ACCESS_OVERVIEW)) { return false; } $tables = DBUtil::getTables(); $news_column = $tables['news_column']; // TODO: Check syntax for other Databases (i.e. Postgres doesn't know YEAR_MONTH) $order = "GROUP BY EXTRACT(YEAR_MONTH FROM $news_column[from]) ORDER BY $news_column[from] DESC"; $date = DateUtil::getDatetime(); $where = "($news_column[from] < '$date' AND $news_column[published_status] = '0')"; $dates = DBUtil::selectFieldArray('news', 'from', $where, $order); return $dates; }
/** * Importa centres a partir d'un csv a la base de dades de Sirius * * Els centres ja existents (codi) els actualitza (informació addicional) i afegeix els nous * * @return void Retorna a la funció *modulesetings* amb els missatges d'execució */ public function importaCentres() { if (!SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_ADMIN)) { return LogUtil::registerPermissionError(); } // get input values. Check for direct function call first because calling function might be either get or post if (isset($args) && is_array($args) && !empty($args)) { $confirmed = isset($args['confirmed']) ? $args['confirmed'] : false; } elseif (isset($args) && !is_array($args)) { throw new Zikula_Exception_Fatal(LogUtil::getErrorMsgArgs()); } elseif ($this->request->isGet()) { $confirmed = false; } elseif ($this->request->isPost()) { $this->checkCsrfToken(); $confirmed = $this->request->request->get('confirmed', false); } if ($confirmed) { // get other import values $importFile = $this->request->files->get('importFile', isset($args['importFile']) ? $args['importFile'] : null); $fileName = $importFile['name']; $importResults = ''; if ($fileName == '') { $importResults = $this->__("No heu triat cap fitxer."); } elseif (FileUtil::getExtension($fileName) != 'csv') { $importResults = $this->__("L'extensió del fitxer ha de ser csv."); } elseif (!$file_handle = fopen($importFile['tmp_name'], 'r')) { $importResults = $this->__("No s'ha pogut llegir el fitxer csv."); } else { $caps = array( 'CODI_ENTITAT' => 'CODI_ENTITAT', 'CODI_TIPUS_ENTITAT'=> 'CODI_TIPUS_ENTITAT', 'NOM_ENTITAT' => 'NOM_ENTITAT', 'NOM_LOCALITAT' => 'NOM_LOCALITAT', 'NOM_DT' => 'NOM_DT', 'CODI_DT' => 'CODI_DT', 'NOM_TIPUS_ENTITAT' => 'NOM_TIPUS_ENTITAT' ); while (!feof($file_handle)) { $line = fgetcsv($file_handle, 1024, ';', '"'); if ($line != '') { $lines[] = $line; } } fclose($file_handle); // $centres = DBUtil::selectFieldArray('cataleg_centres', 'CODI_ENTITAT'); $updateCentres = array(); $insertCentres = array(); foreach ($lines as $line_num => $line) { if ($line_num != 0) { if (count($lines[0]) != count($line)) { $importResults .= $this->__("<div>Hi ha registres amb un número de camps incorrecte.</div>"); } else { if (in_array($line[0], $centres)) { $updateCentres[] = array_combine($lines[0], $line); } else { $insertCentres[] = array_combine($lines[0], $line); } } } else { $difs = array_diff($line, $caps); if (count($line) != count(array_unique($line))) { $importResults = $this->__("La capçalera del csv té columnes repetides."); } elseif (!in_array('CODI_ENTITAT', $line)) { $importResults = $this->__("El csv ha de tenir obligatòriament el camp CODI_ENTITAT."); } elseif ($line[0] != 'CODI_ENTITAT') { $importResults = $this->__("El camp obligatori CODI_ENTITAT ha d'ocupar el primer lloc."); } elseif (!empty($difs)) { $importResults = $this->__("<div>El csv té camps incorrectes.</div>"); } } } } if ($importResults == '') { $inserts = count($insertCentres); $updates = count($updateCentres); DBUtil::insertObjectArray($insertCentres, 'cataleg_centres'); DBUtil::updateObjectArray($updateCentres, 'cataleg_centres', 'CODI_ENTITAT'); // the users have been imported successfully $this->registerStatus($this->__('Els centres s\'han importat correctament')); $this->registerStatus($this->__('Centres actualitzats: ' . $updates . ' - Centres nous: ' . $inserts)); //$this->redirect(ModUtil::url($this->name, 'admin', 'modulesettings')); return system::redirect(ModUtil::url('Cataleg', 'admin', 'modulesettings')); } } // shows the form $post_max_size = ini_get('post_max_size'); return $this->view->assign('importResults', isset($importResults) ? $importResults : '') ->assign('post_max_size', $post_max_size) ->fetch('admin/Cataleg_admin_importaCentres.tpl'); }
function mediashare_userapi_getFirstItemIdInAlbum($args) { // Check access if (!SecurityUtil::checkPermission('mediashare::', '::', ACCESS_READ)) { return LogUtil::registerPermissionError(); } $dom = ZLanguage::getModuleDomain('mediashare'); // Argument check if (!isset($args['albumId'])) { return LogUtil::registerError(__f('Missing [%1$s] in \'%2$s\'', array('albumId', 'userapi.getFirstItemIdInAlbum'), $dom)); } $albumId = (int) $args['albumId']; $pntable = pnDBGetTables(); $mediaColumn = $pntable['mediashare_media_column']; $where = "{$mediaColumn['parentAlbumId']} = '{$albumId}'"; $orderby = "{$mediaColumn['createdDate']} DESC"; $media = DBUtil::selectFieldArray('mediashare_media', 'id', $where, $orderby); if ($media === false) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('userapi.getFirstItemInAlbum', 'Could not retrieve the album information.'), $dom)); } if (!$media) { return true; } return $media[0]; }
/** * Update the IWforums module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @author Josep Ferràndiz Farré (jferran6@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { switch (true) { case ($oldversion < '3.0.0'): //ADD new fields to tables $c = "ALTER TABLE `IWforums_msg` ADD `iw_onTop` TINYINT (4) NOT NULL DEFAULT '0'"; if (!DBUtil::executeSQL($c)) { return false; } //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWforums'", '', false, ''); $newVarsNames = Array('urladjunts', 'avatarsVisible', 'smiliesActive'); $newVars = Array('urladjunts' => 'forums', 'avatarsVisible' => 1, 'smiliesActive' => 1); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } case ($oldversion == '3.0.0'): $sql = "ALTER TABLE `IWforums_definition` ADD `longDescriu` LONGTEXT NOT NULL Default ''"; $connection = Doctrine_Manager::getInstance()->getConnection('default'); $stmt = $connection->prepare($sql); try { $stmt->execute(); } catch (Exception $e) { LogUtil::registerError($e->getMessage()); return false; } $this->setVar('restyledTheme', '1'); HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles()); case ($oldversion == '3.0.1'): $connection = $this->entityManager->getConnection(); $sqlStatements = array(); $sqlStatements[] = "ALTER TABLE `IWforums_definition` ADD `subscriptionMode` TINYINT(4) DEFAULT '1'"; $sqlStatements[] = "ALTER TABLE `IWforums_definition` ADD `subscribers` LONGTEXT"; $sqlStatements[] = "ALTER TABLE `IWforums_definition` ADD `noSubscribers` LONGTEXT"; foreach ($sqlStatements as $sql) { $stmt = $connection->prepare($sql); try { $stmt->execute(); } catch (Exception $e) { } } } return true; }
/** * Build a list of objects which are mapped to the specified categories. * * @param string $tablename Treated table reference. * @param string $categoryFilter The category list to use for filtering. * @param boolean $returnArray Whether or not to return an array (optional) (default=false). * * @return mixed The resulting string or array. */ private static function _generateCategoryFilter($tablename, $categoryFilter, $returnArray = false) { if (!$categoryFilter) { return ''; } if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) { return ''; } // check the meta data if (isset($categoryFilter['__META__']['module'])) { $modname = $categoryFilter['__META__']['module']; } else { $modname = ModUtil::getName(); } // check operator to use // when it's AND, the where contains subqueries if (isset($categoryFilter['__META__']['operator']) && in_array(strtolower($categoryFilter['__META__']['operator']), array('and', 'or'))) { $op = strtoupper($categoryFilter['__META__']['operator']); } else { $op = 'OR'; } unset($categoryFilter['__META__']); // get the properties IDs in the category register $propids = CategoryRegistryUtil::getRegisteredModuleCategoriesIds($modname, $tablename); // build the where clause $n = 1; // subquery counter $catmapobjtbl = 'categories_mapobj'; $where = array(); foreach ($categoryFilter as $property => $category) { $prefix = ''; if ($op == 'AND') { $prefix = "table{$n}."; } // this allows to have an array of categories IDs if (is_array($category)) { $wherecat = array(); foreach ($category as $cat) { $wherecat[] = "{$prefix}category_id='" . DataUtil::formatForStore($cat) . "'"; } $wherecat = '(' . implode(' OR ', $wherecat) . ')'; // if there's only one category ID } else { $wherecat = "{$prefix}category_id='" . DataUtil::formatForStore($category) . "'"; } // process the where depending of the operator if ($op == 'AND') { $where[] = "obj_id IN (SELECT {$prefix}obj_id FROM {$catmapobjtbl} table{$n} WHERE {$prefix}reg_id = '" . DataUtil::formatForStore($propids[$property]) . "' AND {$wherecat})"; } else { $where[] = "(reg_id='" . DataUtil::formatForStore($propids[$property]) . "' AND {$wherecat})"; } $n++; } $where = "tablename='" . DataUtil::formatForStore($tablename) . "' AND (" . implode(" {$op} ", $where) . ')'; // perform the query $objIds = DBUtil::selectFieldArray('categories_mapobj', 'obj_id', $where); // this ensures that we return an empty set if no objects are mapped to the requested categories if (!$objIds) { $objIds[] = -1; } if ($returnArray) { return $objIds; } return implode(',', $objIds); }
/** * Get auth info. * * @param integer $user User Id. * * @return array Two element array of user and group permissions. */ public static function getAuthInfo($user = null) { // Table columns we use - ModUtil::dbInfoLoad is done in pnInit $dbtable = DBUtil::getTables(); $groupmembershipcolumn = $dbtable['group_membership_column']; $grouppermcolumn = $dbtable['group_perms_column']; // Empty arrays $groupperms = array(); $uids[] = -1; // Get user ID if (!isset($user)) { if (!UserUtil::isLoggedIn()) { // Unregistered UID $uids[] = 0; $vars['Active User'] = '******'; } else { $uids[] = UserUtil::getVar('uid'); $vars['Active User'] = UserUtil::getVar('uid'); } } else { $uids[] = $user; $vars['Active User'] = $user; } $uids = implode(',', $uids); // Get all groups that user is in $where = "WHERE {$groupmembershipcolumn['uid']} IN (" . DataUtil::formatForStore($uids) . ')'; $fldArray = DBUtil::selectFieldArray('group_membership', 'gid', $where); if ($fldArray === false) { return $groupperms; } static $usergroups = array(); if (!$usergroups) { $usergroups[] = -1; if (!UserUtil::isLoggedIn()) { $usergroups[] = 0; // Unregistered GID } } $allgroups = array_merge($usergroups, $fldArray); $allgroups = implode(',', $allgroups); // Get all group permissions $where = "WHERE {$grouppermcolumn['gid']} IN (" . DataUtil::formatForStore($allgroups) . ')'; $orderBy = "ORDER BY {$grouppermcolumn['sequence']}"; $objArray = DBUtil::selectObjectArray('group_perms', $where, $orderBy); if (!$objArray) { return $groupperms; } foreach ($objArray as $obj) { $component = self::_fixsecuritystring($obj['component']); $instance = self::_fixsecuritystring($obj['instance']); $level = self::_fixsecuritystring($obj['level']); // Search/replace of special names preg_match_all('/<([^>]+)>/', $instance, $res); $size = count($res[1]); for ($i = 0; $i < $size; $i++) { $instance = preg_replace('/<([^>]+)>/', $vars[$res[1][$i]], $instance, 1); } $groupperms[] = array('component' => $component, 'instance' => $instance, 'level' => $level); } // we've now got the permissions info $GLOBALS['authinfogathered'][$user] = 1; return $groupperms; }
public function sincronize(){ $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWusers::', '::', ACCESS_ADMIN)); $users = DBUtil::selectFieldArray('users', 'uid'); $iwUsers = DBUtil::selectFieldArray('IWusers', 'uid'); $add = array_diff($users, $iwUsers); $del = array_diff($iwUsers, $users); // Add users if (count($add)) { foreach ($add as $r) { $obj = array(); $obj['uid'] = $r; if (!DBUtil::insertObject($obj, 'IWusers', 'suid')) { return LogUtil::registerError($this->__('Error! Creation attempt failed.')); } } } //Delete users if (count($del)) { foreach ($del as $r) { if (!DBUtil::deleteWhere('IWusers', 'iw_uid =' . $r)) { return LogUtil::registerError($this->__('Error! Deletion attempt failed.')); } } } return true; }
/** * Return a string list of user-ids for the specified group. * * @param integer $gid The group ID for which we want the users. * * @return array An array of user IDs. */ public static function getUsersForGroup($gid) { if (!$gid) { return array(); } $where = "WHERE gid = '" . DataUtil::formatForStore($gid) . "'"; return DBUtil::selectFieldArray('group_membership', 'uid', $where); }
function mediashare_editapi_getAccessGroups($args) { $dom = ZLanguage::getModuleDomain('mediashare'); $groups = DBUtil::selectFieldArray('groups', 'name', '', 'name ASC', false, 'gid'); if ($groups === false) { return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('editapi.getAccessGroups', 'Could not retrieve the groups information.'), $dom)); } $result = array(); $result[] = array('groupId' => -1, 'groupName' => __('Everybody', $dom)); foreach ($groups as $gid => $gname) { $result[] = array('groupId' => $gid, 'groupName' => $gname); } return $result; }
/** * Update the IWmain module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { switch ($oldversion) { case ($oldversion < '3.0.0'): // create new needed tables and index if (!DBUtil::createTable('IWmain_logs')) return false; $table = DBUtil::getTables(); $c = $table['IWmain_logs_column']; if (!DBUtil::createIndex($c['moduleName'], 'IWmain_logs', 'moduleName')) return false; if (!DBUtil::createIndex($c['visible'], 'IWmain_logs', 'visible')) return false; //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWmain'", '', false, ''); $newVarsNames = Array('url', 'email', 'documentRoot', 'extensions', 'maxsize', 'usersvarslife', 'cronHeaderText', 'cronFooterText', 'showHideFiles', 'URLBase'); $newVars = Array('url' => 'https://github.com/intraweb-modules13/IWmain', 'email' => '*****@*****.**', 'documentRoot' => 'data', 'extensions' => 'odt|ods|odp|zip|pdf|doc|jpg|gif|txt', 'maxsize', '1000000', 'usersvarslife' => '60', 'cronHeaderText' => $this->__('Header text of the cron automatic emails with the new things to see'), 'cronFooterText' => $this->__('Footer text of the email'), 'showHideFiles' => '0', 'captchaPrivateCode' => '', 'captchaPublicCode' => '', 'URLBase' => System::getBaseUrl()); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } case '3.0.0': // Clean upgrade. Only fix iwcron problems and table definitions to run with IWusers 3.1.0 case '3.0.1': // Add new vars $this->setVar('cronPasswordActive', false) ->setVar('cronPasswrodString','') ->delVar('showHideFiles') ->setVar('cronSubjectText', $this->__('User Reports')) ->setVar('crAc_UserReports', false) ->setVar('crAc_UR_IWforums', false) ->setVar('crAc_UR_IWmessages', false) ->setVar('crAc_UR_IWforms', false) ->setVar('crAc_UR_IWnoteboard', false) ->setVar('crAc_UR_IWforums_hd', '') ->setVar('crAc_UR_IWmessages_hd', '') ->setVar('crAc_UR_IWforms_hd', '') ->setVar('crAc_UR_IWnoteboard_hd', '') ->setVar('everybodySubscribed', true) ->setVar('cronURfreq', '0'); } return true; }
/** * Update the IWnoteboard module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { switch ($oldversion) { case($oldversion < '3.0.0'): // Delete unneded columns $c = array(); $c[] = "ALTER TABLE `IWnoteboard` DROP `iw_public` "; $c[] = "ALTER TABLE `IWnoteboard` DROP `iw_sharedFrom` "; $c[] = "ALTER TABLE `IWnoteboard` DROP `iw_sharedId` "; foreach ($c as $sql) { DBUtil::executeSQL($sql); } // Update z_blocs table $c = "UPDATE blocks SET bkey = 'Nbheadlines' WHERE bkey = 'nbheadlines'"; if (!DBUtil::executeSQL($c)) { return false; } $c = "UPDATE blocks SET bkey = 'Nbtopics' WHERE bkey = 'nbtopics'"; if (!DBUtil::executeSQL($c)) { return false; } //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWnoteboard'", '', false, ''); $newVarsNames = Array('grups', 'permisos', 'marcat', 'verifica', 'caducitat', 'repperdefecte', 'colorrow1', 'colorrow2', 'colornewrow1', 'colornewrow2', 'attached', 'notRegisteredSeeRedactors', 'multiLanguage', 'topicsSystem', 'shipHeadersLines', 'notifyNewEntriesByMail', 'editPrintAfter', 'notifyNewCommentsByMail', 'commentCheckedByDefault', 'smallAvatars'); $newVars = Array('grups' => '', 'permisos' => '', 'marcat' => '', 'verifica' => '', 'caducitat' => '30', 'repperdefecte' => '1', 'colorrow1' => '#FFFFFF', 'colorrow2' => '#FFFFCC', 'colornewrow1' => '#FFCC99', 'colornewrow2' => '#99FFFF', 'attached' => 'noteboard', 'notRegisteredSeeRedactors' => '1', 'multiLanguage' => '0', 'topicsSystem' => '0', 'shipHeadersLines' => '0', 'notifyNewEntriesByMail' => '0', 'editPrintAfter' => '-1', 'notifyNewCommentsByMail' => '1', 'commentCheckedByDefault' => '1', 'smallAvatars' => '0'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } case '3.0.0': HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles()); case '3.0.1': return true; } }
/** * Get selector by table field. * * @param string $modname Module name. * @param string $tablekey Table name. * @param string $name Select field name. * @param string $field Field name. * @param string $where Where clause. * @param string $sort Sort clause. * @param string $selectedValue Selected value. * @param string $defaultValue Value for "default" option. * @param string $defaultText Text for "default" option. * @param string $allValue Value for "all" option. * @param string $allText Text for "all" option. * @param string $assocKey Key for associative array. * @param boolean $distinct Use distinct for selection. * @param boolean $submit Submit on choose. * @param boolean $disabled Add Disabled attribute to select. * @param integer $truncate Truncate field to given length. * @param integer $multipleSize Size for multiple selects. * * @return string The rendered output. */ public static function getSelector_FieldArray($modname, $tablekey, $name, $field = 'id', $where = '', $sort = '', $selectedValue = '', $defaultValue = 0, $defaultText = '', $allValue = 0, $allText = '', $assocKey = '', $distinct = false, $submit = true, $disabled = false, $truncate = 0, $multipleSize = 1) { if (!$tablekey) { return z_exit(__f('Invalid %1$s [%2$s] passed to %3$s.', array('tablekey', $modname, 'HtmlUtil::getSelector_FieldArray'))); } if (!$name) { return z_exit(__f('Invalid %1$s [%2$s] passed to %3$s.', array('name', $name, 'HtmlUtil::getSelector_FieldArray'))); } if ($modname) { ModUtil::dbInfoLoad($modname, '', true); } $fa = DBUtil::selectFieldArray($tablekey, $field, $where, $sort, $distinct, $assocKey); $data = array(); foreach ($fa as $k => $v) { if ($v) { if ($truncate > 0 && strlen($v) > $truncate) { $v = StringUtil::getTruncatedString($v, $truncate); } $data[$k] = $v; } } return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, $allValue, $allText, $submit, $disabled, $multipleSize); }
/** * Update the IWmessages module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { switch ($oldversion) { case($oldversion < '3.0.0'): //Array of names $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWmessages'", '', false, ''); $newVarsNames = Array('groupsCanUpdate', 'uploadFolder', 'multiMail', 'limitInBox', 'limitOutBox', 'dissableSuggest', 'smiliesActive'); $newVars = Array('groupsCanUpdate' => '$', 'uploadFolder' => 'messages', 'multiMail' => '$', 'limitInBox' => '50', 'limitOutBox' => '50', 'dissableSuggest' => '0', 'smiliesActive' => '1'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } case '3.0.0': HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles()); case '3.0.1': } return true; }
/** * Update the IWforms module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @return bool true if successful, false otherwise */ public function upgrade($oldversion) { switch ($oldversion) { case ($oldversion < '3.0.0'): //ADD new fields to tables $c1 = "ALTER TABLE `IWforms_definition` ADD `iw_returnURL` VARCHAR (150) NOT NULL"; if (!DBUtil::executeSQL($c1)) { return false; } $c2 = "ALTER TABLE `IWforms_definition` ADD `iw_filesFolder` VARCHAR (25) NOT NULL"; if (!DBUtil::executeSQL($c2)) { return false; } $c3 = "ALTER TABLE `IWforms_definition` ADD `iw_lang` VARCHAR (2) NOT NULL DEFAULT ''"; if (!DBUtil::executeSQL($c3)) { return false; } // Update z_blocs table $c4 = "UPDATE blocks SET bkey = 'Formnote' WHERE bkey = 'formnote'"; if (!DBUtil::executeSQL($c4)) { return false; } $c5 = "UPDATE blocks SET bkey = 'Formslist' WHERE bkey = 'formslist'"; if (!DBUtil::executeSQL($c5)) { return false; } // serialize bloc Formslist content $where = "bkey='Formslist'"; $items = DBUtil::selectObjectArray('blocks', $where, '', '-1', '-1'); foreach ($items as $item) { $valuesArray = explode('---', $item['url']); $categories = $valuesArray[0]; $listBox = $valuesArray[1]; $serialized = serialize(array('categories' => $categories, 'listBox' => $listBox)); $c = "UPDATE blocks SET content = '$serialized', url='' WHERE bid = $item[bid]"; if (!DBUtil::executeSQL($c)) { return false; } } //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWforms'", '', false, ''); $newVarsNames = Array('characters', 'resumeview', 'newsColor', 'viewedColor', 'completedColor', 'validatedColor', 'fieldsColor', 'contentColor', 'attached', 'publicFolder'); $newVars = Array('characters' => '15', 'resumeview' => '0', 'newsColor' => '#90EE90', 'viewedColor' => '#FFFFFF', 'completedColor' => '#D3D3D3', 'validatedColor' => '#CC9999', 'fieldsColor' => '#ADD8E6', 'contentColor' => '#FFFFE0', 'attached' => 'forms', 'publicFolder' => 'forms/public'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } case '3.0.0': DBUtil::changeTable('IWforms_definition'); case '3.0.1': //Implement Scribite Hooks HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles()); //Templates to tpl $commands = array(); $commands[] ="ALTER TABLE IWforms_definition ALTER COLUMN iw_skinFormTemplate SET DEFAULT 'IWforms_user_new.tpl'"; $commands[] ="ALTER TABLE IWforms_definition ALTER COLUMN iw_skinTemplate SET DEFAULT 'IWforms_user_read.tpl'"; $commands[] ="ALTER TABLE IWforms_definition ALTER COLUMN iw_skinNoteTemplate SET DEFAULT 'IWforms_user_read.tpl'"; // Load DB connection $dbEvent = new Zikula_Event('doctrine.init_connection'); $connection = $this->eventManager->notify($dbEvent)->getData(); foreach ($commands as $sql) { $stmt = $connection->prepare($sql); $stmt->execute(); } case '3.0.2': } return true; }
/** * Find who is online. * * @param unknown_type $args * * @return mixed array of users, or false. */ public function whosonline() { $dbtable = \DBUtil::getTables(); $col = $dbtable['session_info_column']; $activetime = time() - \System::getVar('secinactivemins') * 60; $where = "WHERE {$col['uid']} != 0 AND {$col['lastused']} > {$activetime} GROUP BY {$col['uid']}"; $fa = \DBUtil::selectFieldArray('session_info', 'uid', $where, '', true); $items = array(); foreach ($fa as $f) { $items[] = array('uid' => $f); } return $items; }
function view() { // Private Address Book mode, for users only - commented, because access for registered/unregistered users can be set in site permissions! if (!UserUtil::isLoggedIn() && ModUtil::getVar('AddressBook', 'globalprotect') == 1) { return LogUtil::registerError($this->__f('This website require it\'s users to be registered to use the address book.<br />Register for free <a href="%1$s">here</a>, or <a href=\\"%1$s\\">log in</a> if you are already registered.', array(ModUtil::url('Users', 'user', 'view')))); } // security check if (!SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_READ)) { return LogUtil::registerPermissionError(); } $ot = FormUtil::getPassedValue('ot', 'address', 'GET'); $startnum = FormUtil::getPassedValue('startnum', 1, 'GET'); $pagesize = ModUtil::getVar('AddressBook', 'itemsperpage', 30); $letter = FormUtil::getPassedValue('letter', 0); $sort = FormUtil::getPassedValue('sort', ModUtil::getVar('AddressBook', 'addressbooktype') == 1 ? 'sortname ASC' : 'sortcompany ASC'); $search = FormUtil::getPassedValue('search', 0); $category = FormUtil::getPassedValue('category', 0); $private = FormUtil::getPassedValue('private', 0); if (empty($sort)) { if (ModUtil::getVar('AddressBook', 'addressbooktype') == 1) { $sort = "sortname ASC"; } else { $sort = "sortcompany ASC"; } } else { if (ModUtil::getVar('AddressBook', 'addressbooktype') == 1) { if (strpos($sort, 'sortname') === false) { $sort .= ", sortname ASC"; } } else { if (strpos($sort, 'sortcompany') === false) { $sort .= ", sortcompany ASC"; } } } if ($ot == 'favourite') { $sort = ''; } // Get user id if (UserUtil::isLoggedIn()) { $user_id = UserUtil::getVar('uid'); } else { $user_id = 0; } $this->view->setCacheId('view|cat_' . $category . '|ot' . $ot . '_stnum' . $startnum . '_itpg' . $pagesize . '_let' . $letter . '_sort' . $sort . '_prv' . $private . '_srch' . $search . '|uid_' . $user_id); $template = 'user_view.tpl'; if ($this->view->is_cached($template)) { return $this->view->fetch($template); } // build the where clause $where = ''; $ztable = DBUtil::getTables(); $address_table = $ztable['addressbook_address']; $address_column =& $ztable['addressbook_address_column']; // admin always sees all records but favourites if (SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) { if ($ot == "favourite") { $where .= "(fav_user_id={$user_id})"; } else { $where .= "({$address_column['user_id']} IS NOT NULL)"; } } else { // global protect - users see only their own records (admin sees all) if (ModUtil::getVar('AddressBook', 'globalprotect') == 1 && !SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) { if ($ot == "favourite") { $where = "(fav_user_id={$user_id})"; } else { $where = "({$address_column['user_id']}={$user_id})"; } } else { // if private = 1, show only private records if ($private == 1) { if ($ot == "favourite") { $where = "(fav_user_id={$user_id} AND {$address_column['private']} = 1)"; } else { $where = "({$address_column['user_id']}={$user_id} AND {$address_column['private']} = 1)"; } } else { // if private = 0, show all records if ($ot == "favourite") { $where = "(fav_user_id={$user_id})"; } else { $where = "(({$address_column['private']} = 0) OR ({$address_column['user_id']}={$user_id} AND {$address_column['private']} = 1))"; } } } } // typecasting / security if (!is_string($letter)) { $letter = false; } // filter for abc pager if ($letter && $ot == "address") { if ($sort && strpos($sort, 'ompany')) { $where .= " AND {$address_column['sortcompany']} LIKE '" . DataUtil::formatForStore($letter) . "%'"; } else { $where .= " AND {$address_column['sortname']} LIKE '" . DataUtil::formatForStore($letter) . "%'"; } } // filter for abc pager in favourite mode if ($letter && $ot == "favourite") { if ($sort && strpos($sort, 'ompany')) { $fav_where = "{$address_column['sortcompany']} LIKE '" . DataUtil::formatForStore($letter) . "%'"; } else { $fav_where = "{$address_column['sortname']} LIKE '" . DataUtil::formatForStore($letter) . "%'"; } $fav_data = DBUtil::selectFieldArray("addressbook_address", "id", $fav_where); if (count($fav_data) > 0) { $fav_list = implode(',', $fav_data); $where .= " AND fav_adr_id IN ({$fav_list})"; } else { // dummy, no records were found $where .= " AND fav_adr_id = 0"; } } // filter for category if ($category) { $where .= " AND {$address_column['cat_id']} = {$category}"; } // Inactive status is visible to admins only if ($ot == "address" && !SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) { $where .= " AND {$address_column['status']} = 1"; } // Filter by language if ($ot == "address") { $where .= " AND ({$address_column['language']} = '' OR {$address_column['language']} = '" . DataUtil::formatForStore(ZLanguage::getLanguageCode()) . "')"; } // filter for search if ($search) { LogUtil::registerStatus($this->__('Current search term: ') . $search); // typecasting / security if (is_string($search)) { $where .= " AND ({$address_column['lname']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['fname']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['company']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['title']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['city']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['address1']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['address2']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['zip']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['country']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['state']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['note']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['contact_1']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['contact_2']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['contact_3']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['contact_4']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n OR {$address_column['contact_5']} LIKE '%" . DataUtil::formatForStore($search) . "%')"; } // and now the custom fields $cus_where = ""; $cus_sort = "cus_pos ASC"; $cus_Array = new AddressBook_DBObject_CustomfieldArray(); $customfields = $cus_Array->get($cus_where, $cus_sort); foreach ($customfields as $cus) { if (!strstr($cus['type'], 'tinyint') && !strstr($cus['type'], 'smallint')) { $the_name = 'adr_custom_' . $cus['id']; if (strstr($cus['type'], 'varchar') || strstr($cus['type'], 'text') || strstr($cus['type'], 'dropdown')) { // typecasting / security if (is_string($search)) { $where .= " OR {$the_name} LIKE '%" . DataUtil::formatForStore($search) . "%'"; } } if (strstr($cus['type'], 'int')) { // typecasting / security if (is_int($search)) { $where .= " OR {$the_name} = {$search}"; } } if (strstr($cus['type'], 'decimal')) { // typecasting / security if (is_numeric($search)) { $where .= " OR {$the_name} = {$search}"; } } } } } // get the result $class = 'AddressBook_DBObject_' . ucfirst($ot) . 'Array'; if (!class_exists($class)) { return z_exit($this->__f('Error! Unable to load class [%s]', $ot)); } $objectArray = new $class(); $data = $objectArray->get($where, $sort, $startnum - 1, $pagesize); $objcount = $objectArray->getCount($where); $catregistry = CategoryRegistryUtil::getRegisteredModuleCategories('AddressBook', 'addressbook_address'); $this->view->assign('catregistry', $catregistry); $this->view->assign('ot', $ot); $this->view->assign('objectArray', $data); $this->view->assign('startnum', $startnum); $this->view->assign('letter', $letter); $this->view->assign('category', $category); $this->view->assign('categorydata', CategoryUtil::getCategoryByID($category)); $this->view->assign('private', $private); $this->view->assign('search', $search); $this->view->assign('globalprotect', ModUtil::getVar('AddressBook', 'globalprotect')); $this->view->assign('allowprivate', ModUtil::getVar('AddressBook', 'allowprivate')); $this->view->assign('preferences', ModUtil::getVar('AddressBook')); $this->view->assign('pager', array('numitems' => $objcount, 'itemsperpage' => $pagesize)); return $this->view->fetch($template); }
/** ??? * * @param type $args * @return type */ public function getImportAssigns($importId) { //Verificar permisos $this->throwForbiddenUnless(SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_READ)); $where = 'importId = ' . $importId; return DBUtil::selectFieldArray('cataleg_importAssign', 'idsDest', $where, '', false, 'idsOri'); }
/** * Importa, a la taula seleccionada, les dades d'un csv * * Els registres existents s'actualitzen i els nous s'inserten * * @return void (carrega la plantilla per importar/exportar taules) */ public function importaTaula() { // Security check $this->checkCsrfToken(); $this->throwForbiddenUnless(SecurityUtil::checkPermission('Llicencies::', '::', ACCESS_ADMIN)); if ($this->request->isPost()) { $taula = $this->request->request->get('taula_imp', false); $importFile = $this->request->files->get('importFile', null); } if (is_null($importFile)) { LogUtil::registerError(__('No s\'ha pogut processar l\'arxiu. Probablement supera la mida màxima.')); } else { $import = new CsvImporter($importFile['tmp_name'], true, null,';'); $header = $import->getHeader(); $check = ModUtil::apiFunc($this->name, 'admin', 'checkCSV', array('dbTable' => $taula, 'csvHeader' => $header)); // Comprovar capçaleres del csv if (!$check['correcte']) { // Errades a l'arxiu CSV LogUtil::registerError($check['msg']); } else { // Obtenció del contingut del fitxer csv $data = $import->get(); // Obtenció de les dades de la taula $tContent = DBUtil::selectFieldArray($taula, $check['clau']); // echo '<pre> tContent: ';print_r($tContent); echo '</pre>'; LogUtil::registerStatus($check['msg']); //LogUtil::registerStatus(print_r($data,true)); $update = array(); $insert = array(); foreach ($data as $row => $record) { if (in_array($record[$check['clau']], $tContent)) { $update[] = $record; } else { $insert[] = $record; } } $inserts = count($insert); $updates = count($update); $ins = true; $upd = true; if ($inserts) { $ins = (DBUtil::insertObjectArray($insert, $taula) && ($inserts)); $mi = __('S\'han afegit ' . $inserts . ' registres.'); } if ($updates) { $upd = (DBUtil::updateObjectArray($update, $taula, $check['clau'])) && ($updates); $mu = __('S\'han actualitzat ' . $updates . ' registres.'); } if (($ins) && ($upd)) LogUtil::registerStatus(__('La importació de dades cap a la taula:' . $taula . ' s\'ha realitzat correctament.') . " " . $mi . " " . $mu); else LogUtil::registerError(__('No s\'han pogut modificar totes les dades de la taula: ' . $taula)); } } $this->redirect(ModUtil::url('llicencies', 'admin', 'ieTables')); }
/** * Update the IWusers module * @author Albert Pérez Monfort (aperezm@xtec.cat) * @author Jaume Fernàndez Valiente (jfern343@xtec.cat) * @author Josep Ferràndiz Farré (jferran6@xtec.cat) * @return bool true if successful, false otherwise */ public function Upgrade($oldversion) { switch ($oldversion) { case ($oldversion < '3.0.0'): // Add new columns $c = "ALTER TABLE `IWusers` ADD `iw_avatar` VARCHAR(50) NOT NULL"; if (!DBUtil::executeSQL($c)) return false; $c = "ALTER TABLE `IWusers` ADD `iw_newavatar` VARCHAR(50) NOT NULL"; if (!DBUtil::executeSQL($c)) return false; $c = "ALTER TABLE `IWusers` ADD `iw_sex` TINYINT(4) NOT NULL DEFAULT '0'"; if (!DBUtil::executeSQL($c)) return false; // Delete unneded columns $c = array(); $c[] = "ALTER TABLE `IWusers` DROP `iw_mobile` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_fix` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_parentsName` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_address` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_postal` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_identifyCard` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_refUser` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_sendSMS` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_active` "; $c[] = "ALTER TABLE `IWusers` DROP `iw_parentsEMail` "; foreach ($c as $sql) { DBUtil::executeSQL($sql); } // Modify column names $c = array(); $c = "ALTER TABLE `IWusers` CHANGE `zk_obj_status` `pn_obj_status` VARCHAR(1) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT \'A\'"; $c = "ALTER TABLE `IWusers` CHANGE `zk_cr_date` `pn_cr_date` DATETIME NOT NULL DEFAULT \'1970-01-01 00:00:00\'"; $c = "ALTER TABLE `IWusers` CHANGE `zk_cr_uid` `pn_cr_uid` INT(11) NOT NULL DEFAULT \'0\'"; $c = "ALTER TABLE `IWusers` CHANGE `zk_lu_date` `pn_lu_date` DATETIME NOT NULL DEFAULT \'1970-01-01 00:00:00\'"; $c = "ALTER TABLE `IWusers` CHANGE `zk_lu_uid` `pn_lu_uid` INT(11) NOT NULL DEFAULT \'0\'"; $c = "ALTER TABLE `IWusers_friends` CHANGE `zk_obj_status` `pn_obj_status` VARCHAR(1) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT \'A\'"; $c = "ALTER TABLE `IWusers_friends` CHANGE `zk_cr_date` `pn_cr_date` DATETIME NOT NULL DEFAULT \'1970-01-01 00:00:00\'"; $c = "ALTER TABLE `IWusers_friends` CHANGE `zk_cr_uid` `pn_cr_uid` INT(11) NOT NULL DEFAULT \'0\'"; $c = "ALTER TABLE `IWusers_friends` CHANGE `zk_lu_date` `pn_lu_date` DATETIME NOT NULL DEFAULT \'1970-01-01 00:00:00\'"; $c = "ALTER TABLE `IWusers_friends` CHANGE `zk_lu_uid` `pn_lu_uid` INT(11) NOT NULL DEFAULT \'0\'"; foreach ($c as $sql) { if (!DBUtil::executeSQL($sql)) return false; } //Array de noms $oldVarsNames = DBUtil::selectFieldArray("module_vars", 'name', "`modname` = 'IWusers'", '', false, ''); $newVarsNames = Array('friendsSystemAvailable', 'invisibleGroupsInList', 'usersCanManageName', 'allowUserChangeAvatar', 'allowUserSetTheirSex', 'allowUserDescribeTheirSelves', 'avatarChangeValidationNeeded', 'usersPictureFolder'); $newVars = Array('friendsSystemAvailable' => 1, 'invisibleGroupsInList' => '$', 'usersCanManageName' => 0, 'allowUserChangeAvatar' => '1', 'allowUserSetTheirSex' => '0', 'allowUserDescribeTheirSelves' => '1', 'avatarChangeValidationNeeded' => '1', 'usersPictureFolder' => 'photos'); // Delete unneeded vars $del = array_diff($oldVarsNames, $newVarsNames); foreach ($del as $i) { $this->delVar($i); } // Add new vars $add = array_diff($newVarsNames, $oldVarsNames); foreach ($add as $i) { $this->setVar($i, $newVars[$i]); } case '3.0.0': // Add new column $sql = "ALTER TABLE `IWusers` ADD `iw_code` VARCHAR(5)"; if (!DBUtil::executeSQL($sql)){ return false; } case '3.1.0': // For future release } return true; }