function change_cf_order() { if (!SecurityUtil::checkPermission('AddressBook::', "::", ACCESS_ADMIN)) { AjaxUtil::error($this->__('Error! No authorization to access this module.')); } $cf_list = FormUtil::getPassedValue('cf_list'); // add new custom field positions $cfplacements = array(); for ($i = 0; $i < count($cf_list); $i++) { $cfplacements[] = array('id' => $cf_list[$i][id], 'position' => $i + 1); } $res = DBUtil::updateObjectArray($cfplacements, 'addressbook_customfields'); if (!$res) { AjaxUtil::error($this->__('Error! Update attempt failed.')); } return array('result' => true); }
/** * Change the weight of a profile item. * * Parameters passed in via POST, or via GET: * ------------------------------------------ * array profilelist An array of dud item ids for which the weight should be changed. * numeric startnum The desired weight of the first item in the list minus 1 (e.g., if the weight of the first item should be 3 then startnum contains 2) * * @return mixed An AJAX result array containing a result equal to true, or an Ajax error. */ public function changeprofileweight() { $this->checkAjaxToken(); if (!SecurityUtil::checkPermission('Profile::', '::', ACCESS_ADMIN)) { throw new Zikula_Exception_Forbidden($this->__('Sorry! You do not have authorisation for this module.')); } $profilelist = $this->request->getPost()->get('profilelist', $this->request->getGet()->get('profilelist', null)); $startnum = $this->request->getPost()->get('startnum', $this->request->getGet()->get('startnum', null)); if ($startnum < 0) { AjaxUtil::error($this->__f("Error! Invalid '%s' passed.", 'startnum')); } // update the items with the new weights $items = array(); $weight = $startnum + 1; parse_str($profilelist); foreach ($profilelist as $prop_id) { if (empty($prop_id)) { continue; } $items[] = array('prop_id' => $prop_id, 'prop_weight' => $weight); $weight++; } // update the db $res = DBUtil::updateObjectArray($items, 'user_property', 'prop_id'); if (!$res) { throw new Zikula_Exception_Fatal($this->__('Error! Could not save your changes.')); } return new Zikula_Response_Ajax(array('result' => true)); }
/** * 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')); }
/** * Purge the permalink fields in the Feeds table * @return bool true on success, false on failure */ public function purgepermalinks($args) { // Security check if (!SecurityUtil::checkPermission('Feeds::', '::', ACCESS_ADMIN)) { return LogUtil::registerPermissionError(); } // disable categorization to do this (if enabled) $catenabled = ModUtil::getVar('Feeds', 'enablecategorization'); if ($catenabled) { ModUtil::setVar('Feeds', 'enablecategorization', false); ModUtil::dbInfoLoad('Feeds', 'Feeds', true); } // get all the ID and permalink of the table $data = DBUtil::selectObjectArray('feeds', '', '', -1, -1, 'fid', null, null, array('fid', 'urltitle')); // loop the data searching for non equal permalinks $perma = ''; foreach (array_keys($data) as $fid) { $perma = strtolower(DataUtil::formatPermalink($data[$fid]['urltitle'])); if ($data[$fid]['urltitle'] != $perma) { $data[$fid]['urltitle'] = $perma; } else { unset($data[$fid]); } } // restore the categorization if was enabled if ($catenabled) { ModUtil::setVar('Feeds', 'enablecategorization', true); } if (empty($data)) { return true; // store the modified permalinks } elseif (DBUtil::updateObjectArray($data, 'feeds', 'fid')) { // Let the calling process know that we have finished successfully return true; } else { return false; } }
public function sortModules() { $this->checkAjaxToken(); $this->throwForbiddenUnless(SecurityUtil::checkPermission('Admin::', '::', ACCESS_ADMIN)); $data = $this->request->getPost()->get('modules'); $objects = array(); foreach ($data as $order => $id) { array_push($objects, array("mid" => $id, "order" => $order)); } DBUtil::updateObjectArray($objects, 'admin_module', 'mid'); return new Zikula_Response_Ajax(array()); }
public function applyCsvValues($args){ $this->throwForbiddenUnless(SecurityUtil::checkPermission('IWusers::', '::', ACCESS_DELETE)); $update = isset($args['update'])?$args['update']:null; $insert = isset($args['insert'])?$args['insert']:null; // Upate users table with new values if (!(DBUtil::updateObjectArray($update, 'users', 'uid'))) LogUtil::registerError($this->__('Error! Update attempt failed.')); // Update IWusers table foreach ($update as &$user){ if (DBUtil::updateObject($user, 'IWusers', "iw_uid =".$user['uid'])) $user['action'] = 'm'; // modified //$this->__('Update'); else $user['error']= $user['uname']." - ".$this->__('Error! Update attempt failed.'). " "; } if (count($insert)){ // Create new users in users table if (!(DBUtil::InsertObjectArray($insert, 'users', 'uid'))) LogUtil::registerError($this->__('Error! New user creation attempt failed.')); // Create new users in IWusers table if (!(DBUtil::InsertObjectArray($insert, 'IWusers'))) LogUtil::registerError($this->__('Error! New user creation attempt failed.')); } // Join update and insert arrays and process $allChanges = array_merge($update, $insert); foreach ($allChanges as &$user){ // Process "in" and "out" groups information ModUtil::apiFunc($this->name, 'admin', 'updateUserGroups', $user); // Set user pass if (isset($user['password']) && ($user['password']!="")) { // Validate pass length and pass <> uname or new_uname if (userUtil::validatePassword($user['password'])) { UserUtil::setPassword($user['password'], $user['uid']); } else { // Not a valid password -> error $result['error'][$user['uid']] = $user; $user['error'].= $this->__('Password does not meet the minimum criteria.')." "; } } // Force user change password? if ($forcechgpass) { switch ($user['forcechgpass']) { case 1: UserUtil::setVar('_Users_mustChangePassword', 1, $user['uid']); break; case 0; UserUtil::delVar('_Users_mustChangePassword', $user['uid']); break; } } // Change uname if (isset($user['new_uname']) && ($user['new_uname']!= "") && (!is_null($user['uid']))) { // search repeated uname/new_uname if (!(UserUtil::getIdFromName($user['new_uname']))) { // new_uname not exists proceed with uname change $object['uname'] = $user['new_uname']; //$object['uid'] = $user['uid']; DBUtil::updateObject($object, 'users', "uid=".$user['uid']); //UserUtil::setPassword($user['pass'], $user['uid']); } else { $user['error'].= $this->__f('Duplicated username: %s.', $user['new_uname']); } } } return $allChanges; }
/** * Migrate from version 1.13 to 2.2.0 * * @param string $oldversion The old version from which this upgrade is being processed. * * @return bool True on success; otherwise false. */ public function upgrade113XTablesTo220Tables($oldversion) { if (!DBUtil::changeTable('users_temp')) { return false; } // Get the dbinfo for the new version ModUtil::dbInfoLoad('Users', 'Users'); $nowUTC = new DateTime(null, new DateTimeZone('UTC')); $nowUTCStr = $nowUTC->format(Users_Constant::DATETIME_FORMAT); $serviceManager = ServiceUtil::getManager(); $dbinfoSystem = $serviceManager['dbtables']; $dbinfo113X = Users_tables('1.13'); $dbinfo220 = Users_tables('2.2.0'); $usersOldFields = array( 'user_theme', 'user_viewemail', 'storynum', 'counter', 'hash_method', 'validfrom', 'validuntil', ); $usersOldFieldsDB = array( $dbinfo113X['users_column']['user_theme'], $dbinfo113X['users_column']['user_viewemail'], $dbinfo113X['users_column']['storynum'], $dbinfo113X['users_column']['counter'], $dbinfo113X['users_column']['hash_method'], $dbinfo113X['users_column']['validfrom'], $dbinfo113X['users_column']['validuntil'] ); // Upgrade the tables // Update the users table with new and altered fields. No fields are removed at this point, and no fields // are getting a new data type that is incompatible, so no need to save anything off first. // Also, create the users_verifychg tables at this point. // Merge the global dbtables with the new field information. $tables['users_column'] = $dbinfo220['users_column']; $tables['users_column_def'] = $dbinfo220['users_column_def']; $tables['users_verifychg'] = $dbinfo220['users_verifychg']; $tables['users_verifychg_column'] = $dbinfo220['users_verifychg_column']; $tables['users_verifychg_column_def'] = $dbinfo220['users_verifychg_column_def']; $serviceManager['dbtables'] = array_merge($dbinfoSystem, $tables); // Now change the tables if (!DBUtil::changeTable('users')) { return false; } if (!DBUtil::createTable('users_verifychg')) { return false; } // First users_temp pending email verification records to users_verifychg. $tempColumn = $dbinfo113X['users_temp_column']; $verifyColumn = $dbinfo220['users_verifychg_column']; $usersColumn = $dbinfo220['users_column']; $legalModInfo = ModUtil::getInfoFromName('Legal'); if (($legalModInfo['state'] == ModUtil::STATE_ACTIVE) || ($legalModInfo['state'] == ModUtil::STATE_UPGRADED)) { $legalModuleActive = true; $termsOfUseActive = ModUtil::getVar('Legal', 'termsofuse', false); $privacyPolicyActive = ModUtil::getVar('Legal', 'privacypolicy', false); $agePolicyActive = ($this->getVar('minage', 0) > 0); } else { $legalModuleActive = false; } // Next, users table conversion // We need to convert some information over from the old users table fields, so merge the old field list into // the new one. The order of array_merge parameters is important here! $tables = array('users_column' => array_merge($dbinfo113X['users_column'], $dbinfo220['users_column'])); $serviceManager['dbtables'] = array_merge($dbinfoSystem, $tables); // Do the conversion in PHP we use mb_strtolower, and even if MySQL had an equivalent, there is // no guarantee that another supported DB platform would. $limitNumRows = 100; $limitOffset = 0; $updated = true; $userCount = DBUtil::selectObjectCount('users'); while ($limitOffset < $userCount) { $userArray = DBUtil::selectObjectArray('users', "{$usersColumn['uid']} != 1", '', $limitOffset, $limitNumRows, '', null, null, array('uid', 'uname', 'email', 'pass', 'hash_method', 'user_regdate', 'lastlogin', 'approved_by', 'approved_date')); if (!empty($userArray) && is_array($userArray)) { foreach ($userArray as $key => $userObj) { // force user names and emails to lower case $userArray[$key]['uname'] = mb_strtolower($userArray[$key]['uname']); $userArray[$key]['email'] = mb_strtolower($userArray[$key]['email']); if ($userArray[$key]['user_regdate'] == '1970-01-01 00:00:00') { $userArray[$key]['user_regdate'] = $nowUTCStr; $userArray[$key]['approved_date'] = $nowUTCStr; } else { $userArray[$key]['approved_date'] = $userArray[$key]['user_regdate']; } $userArray[$key]['approved_by'] = 2; // merge hash method for salted passwords, leave salt blank if (!empty($userArray[$key]['pass']) && (strpos($userArray[$key]['pass'], '$$') === false)) { $userArray[$key]['pass'] = (isset($userArray[$key]['hash_method']) ? $userArray[$key]['hash_method'] : '1') . '$$' . $userArray[$key]['pass']; } // Save some disappearing fields as attributes, just in case someone actually used them for // something. But don't overwrite if there already if (!isset($userArray[$key]['__ATTRIBUTES__']) || !is_array($userArray[$key]['__ATTRIBUTES__'])) { $userArray[$key]['__ATTRIBUTES__'] = array(); } foreach ($usersOldFields as $fieldName) { if (($fieldName != 'hash_method') && isset($userArray[$key][$fieldName]) && !empty($userArray[$key][$fieldName]) && !isset($userArray[$key]['__ATTRIBUTES__'][$fieldName])) { $userArray[$key]['__ATTRIBUTES__'][$fieldName] = $userArray[$key][$fieldName]; } } if ($legalModuleActive && ($userArray[$key]['uid'] > 2)) { $userRegDateTime = new DateTime($userArray[$key]['user_regdate'], new DateTimeZone('UTC')); $policyDateTimeStr = $userRegDateTime->format(DATE_ISO8601); if ($termsOfUseActive) { $userArray[$key]['__ATTRIBUTES__']['_Legal_termsOfUseAccepted'] = $policyDateTimeStr; } if ($privacyPolicyActive) { $userArray[$key]['__ATTRIBUTES__']['_Legal_privacyPolicyAccepted'] = $policyDateTimeStr; } if ($agePolicyActive) { $userArray[$key]['__ATTRIBUTES__']['_Legal_agePolicyConfirmed'] = $policyDateTimeStr; } } } } if (!DBUtil::updateObjectArray($userArray, 'users', 'uid', false)) { $updated = false; break; } $limitOffset += $limitNumRows; } if (!$updated) { return false; } $obaColumn = $dbinfoSystem['objectdata_attributes_column']; $limitNumRows = 100; $limitOffset = 0; $updated = true; $userCount = DBUtil::selectObjectCount('users_temp'); // Pass through the users_temp table in chunks of 100 // * ensure unames and email addresses are lower case, while ($limitOffset < $userCount) { $userTempArray = DBUtil::selectObjectArray('users_temp', '', '', $limitOffset, $limitNumRows, '', null, null, array('tid', 'type', 'uname', 'email', 'pass', 'hash_method', 'dynamics', 'comment')); $userArray = array(); if (!empty($userTempArray) && is_array($userTempArray)) { foreach ($userTempArray as $key => $userTempOpj) { // type == 1: User registration pending approval (moderation) if ($userTempArray[$key]['type'] == 1) { $userObj = array(); // Ensure uname and email are lower case $userObj['uname'] = mb_strtolower($userTempArray[$key]['uname']); $userObj['email'] = mb_strtolower($userTempArray[$key]['email']); // Convert pass to salted pass with embedded hash method, leave salt blank $userObj['pass'] = $userTempArray[$key]['hash_method'] . '$$' . $userTempArray[$key]['pass']; $userObj['approved_by'] = 0; $userObj['activated'] = Users_Constant::ACTIVATED_PENDING_REG; if (!empty($userTempArray[$key]['dynamics'])) { $userObj['__ATTRIBUTES__'] = unserialize($userTempArray[$key]['dynamics']); } else { $userObj['__ATTRIBUTES__'] = array(); } if (isset($userObj['dynamics']) && !empty($userObj['dynamics'])) { if (DataUtil::is_serialized($userObj['dynamics'])) { $dynamics = @unserialize($userObj['dynamics']); if (!empty($dynamics) && is_array($dynamics)) { foreach ($dynamics as $key => $value) { $userObj['__ATTRIBUTES__'][$key] = $value; } } } } $userObj['__ATTRIBUTES__']['_Users_isVerified'] = 0; if ($legalModuleActive) { $userRegDateTime = new DateTime($userArray[$key]['user_regdate'], new DateTimeZone('UTC')); $policyDateTimeStr = $userRegDateTime->format(DATE_ISO8601); if ($termsOfUseActive) { $userObj['__ATTRIBUTES__']['_Legal_termsOfUseAccepted'] = $policyDateTimeStr; } if ($privacyPolicyActive) { $userObj['__ATTRIBUTES__']['_Legal_privacyPolicyAccepted'] = $policyDateTimeStr; } if ($agePolicyActive) { $userObj['__ATTRIBUTES__']['_Legal_agePolicyConfirmed'] = $policyDateTimeStr; } } $userArray[] = $userObj; } else { throw new Zikula_Exception_Fatal($this->__f('Unknown users_temp record type: %1$s', array($userTempArray[$key]['type']))); } } } if (!DBUtil::insertObjectArray($userArray, 'users', 'uid', false)) { $updated = false; break; } $limitOffset += $limitNumRows; } if (!$updated) { return false; } // Done upgrading. Let's lose some old fields and tables we no longer need. DBUtil::dropColumn('users', $usersOldFieldsDB); DBUtil::dropTable('users_temp'); // Reset the system tables to the new table definitons, so the rest of the // system upgrade goes smoothly. $dbinfoSystem = $serviceManager['dbtables']; foreach ($dbinfo113X as $key => $value) { unset($dbinfoSystem[$key]); } foreach ($dbinfo220 as $key => $value) { $dbinfoSystem[$key] = $value; } $serviceManager['dbtables'] = $dbinfoSystem; // Update users table for data type change of activated field. if (!DBUtil::changeTable('users')) { return false; } return true; }
/** * 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'); }
protected function contentUpgrade_3_1_0($oldVersion) { $tables = DBUtil::getTables(); // Fix serialisations foreach (array('content' => 'id', 'history' => 'id', 'translatedcontent' => 'contentId') as $table => $idField) { $obj = DBUtil::selectObjectArray('content_' . $table); foreach ($obj as $contentItem) { $data = DataUtil::mb_unserialize($contentItem['data']); $contentItem['data'] = serialize($data); DBUtil::updateObject($contentItem, 'content_' . $table, '', $idField, true); } } // Add active and visiblefor columns in content_content and update tables for indexes etc. DBUtil::changeTable('content_page'); DBUtil::changeTable('content_content'); // Fix language codes // Loop through tables to update foreach (array('page' => 'id', 'translatedcontent' => 'contentId', 'translatedpage' => 'pageId') as $tbl => $idField) { $table = 'content_' . $tbl; $obj = DBUtil::selectObjectArray($table); // if there are records in this table if (count($obj)) { $newobj = array(); // Set up object to insert /// Loop through all records in the table foreach ($obj as $contentItem) { // translate l3 -> l2 $l2 = ZLanguage::translateLegacyCode($contentItem['language']); if ($l2) { $newobj[] = array($idField => $contentItem[$idField], 'language' => $l2); } } // If anything was updated, insert the object(s) if (count($newobj)) { DBUtil::updateObjectArray($newobj, $table, false, $idField); } } // endif count($obj) } return true; }