Exemple #1
0
 public function deletePostProcess($data = null)
 {
     // After delete, it should delete the references to this registry
     // in the categories mapobj table
     $where = "WHERE reg_id = '{$this->_objData[$this->_objField]}'";
     return DBUtil::deleteWhere('categories_mapobj', $where);
 }
Exemple #2
0
 /**
  * Update attributes of a block.
  *
  * @param int $args ['bid'] the ID of the block to update.
  * @param string $args ['title'] the new title of the block.
  * @param string $args ['description'] the new description of the block.
  * @param string $args ['positions'] the new positions of the block.
  * @param string $args ['url'] the new URL of the block.
  * @param string $args ['language'] the new language of the block.
  * @param string $args ['content'] the new content of the block.
  *
  * @return bool true on success, false on failure.
  */
 public function update($args)
 {
     // Optional arguments
     if (!isset($args['url'])) {
         $args['url'] = '';
     }
     if (!isset($args['content'])) {
         $args['content'] = '';
     }
     // Argument check
     if (!isset($args['bid']) || !is_numeric($args['bid']) || !isset($args['content']) || !isset($args['title']) || !isset($args['description']) || !isset($args['language']) || !isset($args['collapsable']) || !isset($args['defaultstate'])) {
         return LogUtil::registerArgsError();
     }
     $block = DBUtil::selectObjectByID('blocks', $args['bid'], 'bid');
     // Security check
     // this function is called durung the init process so we have to check in _ZINSTALLVER
     // is set as alternative to the correct permission check
     if (!System::isInstalling() && !SecurityUtil::checkPermission('Blocks::', "{$block['bkey']}:{$block['title']}:{$block['bid']}", ACCESS_EDIT)) {
         return LogUtil::registerPermissionError();
     }
     $item = array('bid' => isset($args['bid']) ? $args['bid'] : $block['bid'], 'content' => isset($args['content']) ? $args['content'] : $block['content'], 'title' => isset($args['title']) ? $args['title'] : $block['title'], 'description' => isset($args['description']) ? $args['description'] : $block['description'], 'filter' => isset($args['filter']) ? serialize($args['filter']) : $block['filter'], 'url' => isset($args['url']) ? $args['url'] : $block['url'], 'refresh' => isset($args['refresh']) ? $args['refresh'] : $block['refresh'], 'language' => isset($args['language']) ? $args['language'] : $block['language'], 'collapsable' => isset($args['collapsable']) ? $args['collapsable'] : $block['collapsable'], 'defaultstate' => isset($args['defaultstate']) ? $args['defaultstate'] : $block['defaultstate']);
     $res = DBUtil::updateObject($item, 'blocks', '', 'bid');
     if (!$res) {
         return LogUtil::registerError($this->__('Error! Could not save your changes.'));
     }
     // leave unchanged positions as is, delete removed positions from placements table
     // and add placement for new positions
     if (isset($args['positions'])) {
         // Get all existing block positions. We do not use the userapi function here because we need
         // an associative array for the next steps: key = pid (position id)
         $allblockspositions = DBUtil::selectObjectArray('block_positions', null, 'pid', -1, -1, 'pid', null);
         foreach ($allblockspositions as $positionid => $blockposition) {
             if (in_array($positionid, $args['positions'])) {
                 // position name is present in the array submitted from the user
                 $where = "WHERE pid = '" . DataUtil::formatForStore($positionid) . '\'';
                 $blocksinposition = DBUtil::selectObjectArray('block_placements', $where, 'sortorder', -1, -1, 'bid');
                 if (array_key_exists($item['bid'], $blocksinposition)) {
                     // block is already in this position, placement did not change, this means we do nothing
                 } else {
                     // add the block to the given position as last entry (max(sortorder) +1
                     $newplacement = array('pid' => $blockposition['pid'], 'bid' => $item['bid'], 'order' => count($blocksinpositions));
                     $res = DBUtil::insertObject($newplacement, 'block_placements', 'bid', true);
                     if (!$res) {
                         return LogUtil::registerError($this->__('Error! Could not perform the insertion.'));
                     }
                 }
             } else {
                 // position name is NOT present in the array submitted from the user
                 // delete the block id from the placements table for this position
                 $where = '(bid = \'' . DataUtil::formatForStore($item['bid']) . '\' AND pid = \'' . DataUtil::formatForStore($blockposition['pid']) . '\')';
                 $res = DBUtil::deleteWhere('block_placements', $where);
                 if (!$res) {
                     return LogUtil::registerError($this->__('Error! Could not save your changes.'));
                 }
             }
         }
     }
     return true;
 }
 /**
  * Listener for installer.subscriberarea.uninstalled
  *
  * @param Zikula_Event $event
  *
  * @return void
  */
 public static function hookAreaDelete(Zikula_Event $event)
 {
     $areaId = $event['areaid'];
     // Database information
     ModUtil::dbInfoLoad('EZComments');
     $tables = DBUtil::getTables();
     $columns = $tables['EZComments_column'];
     // Get items
     $where = "WHERE {$columns['areaid']} = '" . DataUtil::formatForStore($areaId) . "'";
     DBUtil::deleteWhere('EZComments', $where);
 }
 /**
  * Delete a category registry entry
  *
  * @param string  $modname The module to create a property for.
  * @param integer $entryID The category-id to bind this property to.
  *
  * @return boolean The DB insert operation result code cast to a boolean.
  */
 public static function deleteEntry($modname, $entryID = null)
 {
     if (!isset($modname) || !$modname) {
         return z_exit(__f("Error! Received invalid parameter '%s'", 'modname'));
     }
     $where = "modname='{$modname}'";
     if ($entryID) {
         $where .= " AND id={$entryID}";
     }
     return (bool) DBUtil::deleteWhere('categories_registry', $where);
 }
Exemple #5
0
 function deletefavourite()
 {
     $objectid = FormUtil::getPassedValue('objectid', null, 'POST');
     $userid = FormUtil::getPassedValue('userid', null, 'POST');
     if (!SecurityUtil::checkPermission('AddressBook::', "::", ACCESS_COMMENT)) {
         AjaxUtil::error($this->__('Error! No authorization to access this module.'));
     }
     $ztables = DBUtil::getTables();
     $fav_column = $ztables['addressbook_favourites_column'];
     $where = "{$fav_column['favadr_id']} = '" . DataUtil::formatForStore($objectid) . "' AND {$fav_column['favuser_id']} = '" . DataUtil::formatForStore($userid) . "'";
     DBUtil::deleteWhere('addressbook_favourites', $where);
     return;
 }
Exemple #6
0
 function deleteFile($fileReference)
 {
     $dom = ZLanguage::getModuleDomain('mediashare');
     $pntable = pnDBGetTables();
     $mediadbColumn = $pntable['mediashare_mediadb_column'];
     $fileReference = DataUtil::formatForStore($fileReference);
     $where = "{$mediadbColumn['fileref']} = '{$fileReference}'";
     $result = DBUtil::deleteWhere('mediashare_mediadb', $where);
     if ($result === false) {
         return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('vfsHandlerDB.deleteFile', 'Could not delete the file information.'), $dom));
     }
     return true;
 }
Exemple #7
0
    /**
     * Delete all the group membership of the user
     * @author:     Albert Pérez Monfort (aperezm@xtec.cat)
     * @author: 	Josep Ferràndiz (jferran6@xtec.cat)
     * @param:	none
     * @return:	True if success and false in other case
     */
    public function delUserGroups() {
        // Security check
        if (!SecurityUtil::checkPermission('IWmyrole::', "::", ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        $pntables = DBUtil::getTables();
        $c = $pntables['group_membership_column'];
        $where = "WHERE $c[uid]=" . UserUtil::getVar('uid') . " AND $c[gid] <>" . ModUtil::getVar('IWmyrole', 'rolegroup');

        if (!DBUtil::deleteWhere('group_membership', $where)) {
            return LogUtil::registerError($this->__('Error! Sorry! Deletion attempt failed.'));
        }
        return true;
    }
Exemple #8
0
    public function buida($args) {
        $sid = FormUtil::getPassedValue('sid', isset($args['sid']) ? $args['sid'] : null, 'POST');

        //Comprovem que el par�metre id efectivament hagi arribat
        if (!isset($sid)) {
            LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
            return false;
        }

        //Cridem la funci� get que retorna les dades
        $link = ModUtil::apiFunc('IWbookings', 'user', 'get', array('sid' => $sid));

        //Comprovem que el registre efectivament existeix i, per tant, es podr� esborrar
        if ($link == false) {
            LogUtil::registerError($this->__('The room or equipment was not found'));
            return false;
        }

        //Comprovaci� de seguretat
        if (!SecurityUtil::checkPermission('IWbookings::', "::", ACCESS_ADMIN)) {
            LogUtil::registerError($this->__('You are not allowed to administrate the bookings'));
            return false;
        }

        $pntables = DBUtil::getTables();
        $c = $pntables['IWbookings_column'];
        $where = "WHERE $c[sid]=" . $sid;
        if (!DBUtil::deleteWhere('IWbookings', $where)) {
            return false;
        } else {
            //Retornem true ja que el proc�s ha finalitzat amb �xit
            return true;
        }
    }
Exemple #9
0
 /**
  * Example delete process hook handler.
  *
  * The subject should be the object that was deleted.
  * args[id] Is the is of the object
  * args[caller] is the name of who notified this event.
  *
  * @param Zikula_ProcessHook $hook The hookable event.
  *
  * @return void
  */
 public function processDelete(Zikula_ProcessHook $hook)
 {
     if ($hook->getId() <= 0) {
         return;
     }
     // Security check
     $res = ModUtil::apiFunc('EZComments', 'user', 'checkPermission', array('module' => $hook->getCaller(), 'objectid' => $hook->getId(), 'level' => ACCESS_DELETE));
     if (!$res) {
         return LogUtil::registerPermissionError(ModUtil::url('EZComments', 'admin', 'main'));
     }
     // get db table and column for where statement
     ModUtil::dbInfoLoad('EZComments');
     $tables = DBUtil::getTables();
     $column = $tables['EZComments_column'];
     $mod = DataUtil::formatForStore($hook->getCaller());
     $objectid = DataUtil::formatForStore($hook->getId());
     $areaid = DataUtil::formatForStore($hook->getAreaId());
     $where = "{$column['modname']} = '{$mod}' AND {$column['objectid']} = '{$objectid}' AND {$column['areaid']} = '{$areaid}'";
     DBUtil::deleteWhere('EZComments', $where);
 }
Exemple #10
0
 /**
  * Delete with a where-clause.
  *
  * @param string $where The where-clause to use.
  *
  * @return array|boolean The Object Data.
  */
 public function deleteWhere($where = null)
 {
     if (!$where) {
         return false;
     }
     if (!$this->deletePreProcess()) {
         return false;
     }
     $res = DBUtil::deleteWhere($this->_objType, $where);
     $this->deletePostProcess();
     return $this->_objData;
 }
Exemple #11
0
    /**
     *  Esborra un element indicant el tipus i la seva id
     * 
     * > També s'esborren els registres associats d'altres taules.
     * 
     * @param array $args Array amb els paràmetres de la funció
     *
     * ### Paràmetres de l'array $args:
     * * string **que** Indica allò que volem esborrar: activitat, unitat, catàleg, orientació, ...
     * * integer **id** Identificador de l'element a esborrar
     * 
     * @return boolean true si tot ha anat bé || false en cas d'error
     */
    public function delete($args) {
        // Check permission
        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Cataleg::', '::', ACCESS_DELETE));

        $que = $args['que'] ? $args['que'] : null;
        $id = $args['id'] ? $args['id'] : null;


        if (isset($id)) {
            switch ($que) {
                case 'activitat':
                    $where = 'actId =' . $id;
                    //return LogUtil::registerError($id." -".$que." - WHERE: ". $where);         
                    // Esborrem de la taula activitats

                    if ((DBUtil::deleteWhere('cataleg_activitats', $where)) &&
                            (DBUtil::deleteWhere('cataleg_contactes', $where)) &&
                            (DBUtil::deleteWhere('cataleg_activitatsZona', $where)) &&
                            (DBUtil::deleteWhere('cataleg_centresActivitat', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'cataleg':
                    $where = 'catId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'eix':
                    $where = 'eixId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_eixos', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'subprioritat':
                    $where = 'sprId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_subprioritats', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'impunit':
                    $where = 'impunitId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_unitatsImplicades', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'unitat':
                    $where = 'uniId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_unitats', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'responsable':
                    $where = 'respunitId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_responsables', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'allResponsablesUnitat':
                    $where = 'uniId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_responsables', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'prioritat':
                    $where = 'priId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_prioritats', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'allSubprioritatsPrioritat':
                    $where = 'priId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_subprioritats', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'allImpunitsPrioritat':
                    $where = 'priId =' . $id;
                    if ((DBUtil::deleteWhere('cataleg_unitatsImplicades', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'gtafEntity':
                    $where = "gtafEntityId ='" . $id ."'";
                    if ((DBUtil::deleteWhere('cataleg_gtafEntities', $where)))
                        return true;
                    else
                        return false;
                    break;
                case 'gtafGroup':
                    $where = "gtafGroupId ='" . $id ."'";
                    if ((DBUtil::deleteWhere('cataleg_gtafGroups', $where)))
                        return true;
                    else
                        return false;
                    break;
            }
        }
        return true;
    }
Exemple #12
0
        /**
     * Importa les taules de entitats-gtaf i grups d'entitats a partir d'un csv a la base de dades de Sirius
     * 
     * Esborra el contingut previ de les taules i importa el contingut del fitxer
     * 
     * @return void Retorna a la funció *gtafEntitiesGest* amb els missatges d'execució
     */
    public function importGtafEntities() {
        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;
            $case = isset($args['case']) ? $args['case'] : false;
        } elseif (isset($args) && !is_array($args)) {
            throw new Zikula_Exception_Fatal(LogUtil::getErrorMsgArgs());
        } elseif ($this->request->isGet()) {
            $confirmed = 1;
        } elseif ($this->request->isPost()) {
            $this->checkCsrfToken();
            $confirmed = $this->request->request->get('confirmed', false);
            $case = $this->request->request->get('case',false);
        }
        if ($confirmed == 2) {
            if ($case == 'entities') {
                $caps = array(
                    'gtafEntityId'   => 'gtafEntityId',
                    'nom'            => 'nom',
                    'tipus'          => 'tipus',
                    'gtafGroupId'    => 'gtafGroupId'
                );
                $caps_man = $caps;
                $taula = 'cataleg_gtafEntities';
                $mes = "Importació d'entitats-gtaf";
                $field_id = 'gtafEntityId';
            } else {
                $caps = array(
                    'gtafGroupId'   => 'gtafGroupId',
                    'nom'           => 'nom',
                    'resp_uid'      => 'resp_uid'
                );
                $caps_man = array(
                    'gtafGroupId'   => 'gtafGroupId',
                    'nom'           => 'nom'
                );
                $taula = 'cataleg_gtafGroups';
                $mes = "Importació de grups d'entitats-gtaf";
                $field_id = 'gtafGroupId';
            }
            // 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 {
                while (!feof($file_handle)) {
                    $line = fgetcsv($file_handle, 1024, ';', '"');
                    if ($line != '') {
                        $lines[] = $line;
                    }
                }
                fclose($file_handle);
                //
                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 {
                                $import[] = array_combine($lines[0], $line);
                                $import_id[] = $line[0];
                        }
                    } else {
                        $difs = array_diff($line, $caps);
                        $difs2 = array_diff($caps_man,$line);
                        if (count($line) != count(array_unique($line))) {
                            $importResults .= $this->__("<div>La capçalera del csv té columnes repetides.</div>");
                        } elseif (!in_array($field_id, $line)) {
                            $importResults .= $this->__("<div>Falta el camp obligatori de la clau primària (id).</div>");
                        } elseif ($line[0] != $field_id) {
                            $importResults .= $this->__("<div>El camp obligatori de la clau primària (id) ha d'ocupar el primer lloc.</div>");
                        } elseif (!empty($difs2)) {
                            $importResults .= $this->__("<div>Falten camps obligatoris.</div>");
                        } elseif (!empty($difs)) {
                            $importResults .= $this->__("div>El csv té camps incorrectes.</div>");
                        }
                    }
                }
                if (count($import_id) != count(array_unique($import_id))) $importResults .= $this->__("<div>El fitxer té alguna id repetida.</div>"); 
            }
            
            if ($importResults == '') {
                $old_reg = DBUtil::selectObjectCount($taula);
                DBUtil::deleteWhere($taula);
                $inserts = count($import);
                DBUtil::insertObjectArray($import, $taula);
                $this->registerStatus($mes);
                $this->registerStatus($this->__('La importació s\'ha realitzat correctament'));
                $this->registerStatus($this->__('Registres antics: ' . $old_reg . ' - Registres actuals: ' . $inserts));
                return system::redirect(ModUtil::url('Cataleg', 'admin', 'gtafEntitiesGest'));
            } else {
                $this->view->assign('case',$case);
                $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_importGtafEntities.tpl');
            }
        } elseif ($confirmed == 1){
            // shows the form
            $case = $this->request->query->get('case',false);
            $this->view->assign('case',$case);
            $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_importGtafEntities.tpl');
        } else {
            LogUtil::registerError($this->__('La petició no és vàlida'));
            return system::redirect(ModUtil::url('Cataleg', 'admin', 'gtafEntitiesGest'));
        }
    }
Exemple #13
0
 /**
  * Delete a meta data object.
  *
  * @param array  $obj       The object we wish to delete categorization data for.
  * @param string $tablename The object's tablename.
  * @param string $idcolumn  The object's idcolumn (optional) (default='obj_id').
  *
  * @return The result from the metadata insert operation
  */
 public static function deleteObjectCategories($obj, $tablename, $idcolumn = 'obj_id')
 {
     if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) {
         return false;
     }
     $where = "tablename='" . DataUtil::formatForStore($tablename) . "' AND obj_id='" . DataUtil::formatForStore($obj[$idcolumn]) . "' AND obj_idcolumn='" . DataUtil::formatForStore($idcolumn) . "'";
     $categoriesDeleted = (bool) DBUtil::deleteWhere('categories_mapobj', $where);
     $dbtables = DBUtil::getTables();
     if (isset($dbtables[$tablename])) {
         DBUtil::flushCache($tablename);
     }
     return $categoriesDeleted;
 }
Exemple #14
0
 /**
  * Update module hook information, extended version.
  *
  * @param array $args All parameters passed to this function.
  *                      numeric $args['id'] The id number of the module to update.
  *
  * @deprecated since 1.3.0
  *
  * @return boolean True on success, false on failure.
  */
 public function extendedupdatehooks($args)
 {
     // Argument check
     if (!isset($args['id']) || !is_numeric($args['id'])) {
         return LogUtil::registerArgsError();
     }
     // Security check
     if (!SecurityUtil::checkPermission('Extensions::', "::{$args['id']}", ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     // Rename operation
     $dbtable = DBUtil::getTables();
     $hookscolumn = $dbtable['hooks_column'];
     // Hooks
     // Get module information
     $modinfo = ModUtil::getInfo($args['id']);
     // Delete hook regardless
     $where = "WHERE {$hookscolumn['smodule']} = '" . DataUtil::formatForStore($modinfo['name']) . "'\n                    AND {$hookscolumn['tmodule']} <> ''";
     DBUtil::deleteWhere('hooks', $where);
     $where = "WHERE {$hookscolumn['smodule']} = ''";
     $orderBy = "ORDER BY {$hookscolumn['tmodule']}, {$hookscolumn['smodule']} DESC";
     // read the hooks themselves - the entries in the database that are not connected
     // with a module
     $objArray = DBUtil::selectObjectArray('hooks', $where, $orderBy);
     if ($objArray === false) {
         return false;
     }
     // sort the hooks by action
     $grouped_hooks = array();
     foreach ($objArray as $hookobject) {
         if (!array_key_exists($hookobject['action'], $grouped_hooks)) {
             $grouped_hooks[$hookobject['action']] = array();
         }
         $grouped_hooks[$hookobject['action']][$hookobject['tmodule']] = $hookobject;
     }
     // get hookvalues. This is an array of hookactions with each one
     // containing an array of hooks where the checkbox has been set
     // in short: hookvalues only contains the hooks the that the user
     // want s to activate for the selected module. As a side effect
     // the hooks are sorted :-)
     $hookvalues = FormUtil::getPassedValue('hooks');
     // cycle throught the hookvalues
     foreach ($hookvalues as $action => $actionarray) {
         // reset the sequence
         $sequence = 1;
         foreach ($actionarray as $smodule => $value) {
             $hookobject = $grouped_hooks[$action][$smodule];
             $hookobject['sequence'] = $sequence;
             $hookobject['smodule'] = $modinfo['name'];
             if (DBUtil::insertObject($hookobject, 'hooks') === false) {
                 return false;
             }
             $sequence++;
         }
     }
     return true;
 }
Exemple #15
0
    public function delete($args) {
        //$mdid = FormUtil::getPassedValue('mdid', isset($args['mdid']) ? $args['mdid'] : null, 'POST');
        //$mode = FormUtil::getPassedValue('m', isset($args['m']) ? $args['m'] : null, 'POST');
        $mdid = $args['mdid'];
        $mode = $args['m'];

        //Comprovem que el parï¿œmetre id hagi arribat
        if (!isset($mdid)) {
            return LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
        }

        //Carreguem l'API de l'usuari per carregar les dades del registre
        if (!ModUtil::loadApi('IWtimeframes', 'user')) {
            return LogUtil::registerError($this->__('Error! Could not load module.'));
        }

        //Cridem la funciᅵ get que retorna les dades
        $registre = ModUtil::apiFunc('IWtimeframes', 'user', 'get', array('mdid' => $mdid));

        //Comprovem que el registre efectivament existeix i per tant, es podrᅵ esborrar
        if (empty($registre)) {
            return LogUtil::registerError($this->__('Can not find the timeFrame over which do the action.') . " - " . $registre['nom_marc']);
        }

        //Comprovaciᅵ de seguretat
        if (!SecurityUtil::checkPermission('IWtimeframes::', "$registre[nom_marc]::$mdid", ACCESS_DELETE)) {
            return LogUtil::registerError($this->__('Not authorized to manage timeFrames.'));
        }

        switch ($mode) {
            case 'all': //erase timetable and all the bookings referenced in IWbookings
                // falta esborrar totes les reserves
                if (ModUtil::apifunc('IWtimeframes', 'admin', 'installed', 'IWbookings')){
                    $where = "mdid = " . $mdid; 
                    $rs = array();
                    $rs = DBUtil::selectObjectArray('IWbookings_spaces', $where);
                    foreach ($rs as $item) {
                        DBUtil::deleteWhere('IWbookings', "sid=" . $item['sid']);
                    }
                }
            case 'keep': //keep bookings and reset timeframe
                if (ModUtil::apifunc('IWtimeframes', 'admin', 'installed', 'IWbookings')){
                    // Posem a 0 la referència al marc horari esborrat dels espais afectats
                    ModUtil::apiFunc('IWbookings', 'admin', 'reset_timeframe', $mdid);
                }

            //case 'noref': //delete: timetable
            //    DBUtil::deleteWhere('IWtimeframes_definition', "mdid=" . $mdid);
            //    DBUtil::deleteWhere('IWtimeframes', "mdid=" . $mdid);
        }
        // Esborrem el mac horari
        DBUtil::deleteWhere('IWtimeframes_definition', "mdid=" . $mdid);
        DBUtil::deleteWhere('IWtimeframes', "mdid=" . $mdid);
        //Retornem true ja que el procï¿œs ha finalitzat amb ï¿œxit
        return true;
    }
Exemple #16
0
 /**
  * {@inheritdoc}
  */
 public function gc($lifetime)
 {
     $now = time();
     $inactive = $now - (int) (System::getVar('secinactivemins') * 60);
     $daysold = $now - (int) (System::getVar('secmeddays') * 86400);
     // find the hash length dynamically
     $hash = ini_get('session.hash_function');
     if (empty($hash) || $hash == 0) {
         $sessionlength = 32;
     } else {
         $sessionlength = 40;
     }
     if (System::getVar('sessionstoretofile')) {
         // file based GC
         $path = DataUtil::formatForOS(session_save_path(), true);
         // get files
         $files = array();
         if ($handle = opendir($path)) {
             while (false !== ($file = readdir($handle))) {
                 if ($file != '.' && $file != '..' && strlen($file) == $sessionlength) {
                     // filename, created, last modified
                     $file = "{$path}/{$file}";
                     $files[] = array('name' => $file, 'lastused' => filemtime($file));
                 }
             }
         }
         // check we have something to do
         if (count($files) == 0) {
             return true;
         }
         // do GC
         switch (System::getVar('seclevel')) {
             case 'Low':
                 // Low security - delete session info if user decided not to
                 //                remember themself and session is inactive
                 foreach ($files as $file) {
                     $name = $file['name'];
                     $lastused = $file['lastused'];
                     $session = unserialize(file_get_contents($name));
                     if ($lastused < $inactive && !isset($session['rememberme'])) {
                         unlink($name);
                     }
                 }
                 break;
             case 'Medium':
                 // Medium security - delete session info if session cookie has
                 // expired or user decided not to remember themself and inactivity timeout
                 // OR max number of days have elapsed without logging back in
                 foreach ($files as $file) {
                     $name = $file['name'];
                     $lastused = $file['lastused'];
                     $session = unserialize(file_get_contents($name));
                     if ($lastused < $inactive && !isset($session['rememberme'])) {
                         unlink($name);
                     } elseif ($lastused < $daysold) {
                         unlink($name);
                     }
                 }
                 break;
             case 'High':
                 // High security - delete session info if user is inactive
                 foreach ($files as $file) {
                     $name = $file['name'];
                     $lastused = $file['lastused'];
                     if ($lastused < $inactive) {
                         unlink($name);
                     }
                 }
                 break;
         }
         return true;
     } else {
         // DB based GC
         $dbtable = DBUtil::getTables();
         $sessioninfocolumn = $dbtable['session_info_column'];
         $inactive = DataUtil::formatForStore(date('Y-m-d H:i:s', $inactive));
         $daysold = DataUtil::formatForStore(date('Y-m-d H:i:s', $daysold));
         switch (System::getVar('seclevel')) {
             case 'Low':
                 // Low security - delete session info if user decided not to
                 //                remember themself and inactivity timeout
                 $where = "WHERE {$sessioninfocolumn['remember']} = 0\n                          AND {$sessioninfocolumn['lastused']} < '{$inactive}'";
                 break;
             case 'Medium':
                 // Medium security - delete session info if session cookie has
                 // expired or user decided not to remember themself and inactivity timeout
                 // OR max number of days have elapsed without logging back in
                 $where = "WHERE ({$sessioninfocolumn['remember']} = 0\n                          AND {$sessioninfocolumn['lastused']} < '{$inactive}')\n                          OR ({$sessioninfocolumn['lastused']} < '{$daysold}')\n                          OR ({$sessioninfocolumn['uid']} = 0 AND {$sessioninfocolumn['lastused']} < '{$inactive}')";
                 break;
             case 'High':
             default:
                 // High security - delete session info if user is inactive
                 $where = "WHERE {$sessioninfocolumn['lastused']} < '{$inactive}'";
                 break;
         }
         $res = DBUtil::deleteWhere('session_info', $where);
         return (bool) $res;
     }
 }
Exemple #17
0
 /**
  * Pending action.
  *
  * @param int $args['gid']
  * @param int $args['userid']
  * @param string $args['action']
  *
  * @return boolean
  */
 public function pendingaction($args)
 {
     if (!isset($args['gid']) || !isset($args['userid']) || !isset($args['action'])) {
         return LogUtil::registerArgsError();
     }
     $dbtable = DBUtil::getTables();
     $col = $dbtable['group_applications_column'];
     $where = "WHERE {$col['gid']} = '" . (int) DataUtil::formatForStore($args['gid']) . "'\n              AND   {$col['uid']} = '" . (int) DataUtil::formatForStore($args['userid']) . "'";
     if (!DBUtil::deleteWhere('group_applications', $where)) {
         return LogUtil::registerError($this->__('Error! Could not perform the deletion.'));
     }
     if ($args['action'] == 'accept') {
         $adduser = ModUtil::apiFunc('Groups', 'admin', 'adduser', array('gid' => $args['gid'], 'uid' => $args['userid']));
     }
     // Send message part
     switch ($args['sendtag']) {
         case 1:
             $send = ModUtil::apiFunc('Messages', 'user', 'create', array('to_userid' => $args['userid'], 'subject' => $args['reasontitle'], 'message' => $args['reason']));
             if ($send == false) {
                 LogUtil::registerError($this->__('Error! Could not send the private message to the user.'));
             }
             break;
         case 2:
             if (ModUtil::available('Mailer')) {
                 $send = ModUtil::apiFunc('Mailer', 'user', 'sendmessage', array('toname' => UserUtil::getVar('uname', $args['userid']), 'toaddress' => UserUtil::getVar('email', $args['userid']), 'subject' => $args['reasontitle'], 'body' => $args['reason']));
             } else {
                 $send = System::mail(UserUtil::getVar('email', $args['userid']), $args['reasontitle'], $args['reason'], "From: " . System::getVar('adminmail') . "\nX-Mailer: PHP/" . phpversion(), 0);
             }
             break;
     }
     return true;
 }
Exemple #18
0
    /**
     * Removes a record from the users_verifychg table for a specified uid and changetype.
     *
     * Parameters passed in the $args array:
     * -------------------------------------
     * integer       $args['uid']        The uid of the verifychg record to remove. Required.
     * integer|array $args['changetype'] The changetype(s) of the verifychg record to remove. If more
     *                                          than one type is to be removed, use an array. Optional. If
     *                                          not specifed, all verifychg records for the user will be
     *                                          removed. Note: specifying an empty array will remove none.
     *
     * @param array $args All parameters passed to this function.
     *
     * @return void|bool Null on success, false on error.
     */
    public function resetVerifyChgFor($args)
    {
        if (!isset($args['uid'])) {
            $this->registerError(LogUtil::getErrorMsgArgs());

            return false;
        }
        $uid = $args['uid'];
        if (!is_numeric($uid) || ((int)$uid != $uid) || ($uid <= 1)) {
            $this->registerError(LogUtil::getErrorMsgArgs());

            return false;
        }

        if (!isset($args['changetype'])) {
            $changeType = null;
        } else {
            $changeType = $args['changetype'];
            if (!is_array($changeType)) {
                $changeType = array($changeType);
            } elseif (empty($changeType)) {
                return;
            }
            foreach ($changeType as $theType) {
                if (!is_numeric($theType) || ((int)$theType != $theType) || ($theType < 0)) {
                    $this->registerError(LogUtil::getErrorMsgArgs());

                    return false;
                }
            }
        }

        $dbinfo = DBUtil::getTables();
        $verifyChgColumn = $dbinfo['users_verifychg_column'];

        $where = "WHERE ({$verifyChgColumn['uid']} = {$uid})";
        if (isset($changeType)) {
            $where .= " AND ({$verifyChgColumn['changetype']} IN (" . implode(', ', $changeType) . "))";
        }
        DBUtil::deleteWhere('users_verifychg', $where);
    }
Exemple #19
0
    /**
     * delete a private message
     *
     * @author	 Nathan Codding
     * @Modified by Albert Pï¿œrez Monfort
     * @param 	 $args['msgid'] userid to get private message count for
     * @return   integer   number of items held by this module
     */
    public function delete($args) {
        // Get arguments from argument array
        $msgid = FormUtil::getPassedValue('msgid', isset($args['msgid']) ? $args['msgid'] : null, 'POST');
        $uid = FormUtil::getPassedValue('uid', isset($args['uid']) ? $args['uid'] : null, 'POST');
        $qui = FormUtil::getPassedValue('qui', isset($args['qui']) ? $args['qui'] : null, 'POST');
        // Security check
        if (!SecurityUtil::checkPermission('IWmessages::', '::', ACCESS_OVERVIEW) || !UserUtil::isLoggedIn()) {
            return LogUtil::registerPermissionError();
        }
        // Argument check - make sure that all required arguments are present, if
        // not then set an appropriate error message and return
        if (!isset($msgid) || !is_numeric($msgid) || !isset($uid) || !is_numeric($uid)) {
            return LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
        }

        $pntable = DBUtil::getTables();
        $c = $pntable['IWmessages_column'];
        $where = "$c[msg_id]=$msgid";
        if ($qui == "d") {
            $item = array('del_msg_to' => 1);
            $where .= " AND $c[to_userid] = '" . $uid . "'";
        } else {
            $item = array('del_msg_from' => 1);
            $where .= " AND $c[from_userid] = '" . $uid . "'";
        }
        if (!DBUTil::updateObject($item, 'IWmessages', $where)) {
            return LogUtil::registerError($this->__('Error! Update attempt failed.'));
        }
        $item = ModUtil::apiFunc('IWmessages', 'user', 'get', array('uid' => UserUtil::getVar('uid'),
                    'msgid' => $msgid));
        if (!$item) {
            return LogUtil::registerError($this->__('No such item found.'));
        }
        // only if user_from and user_to have deleted the message this message is deleted from database
        $pntables = DBUtil::getTables();
        $c = $pntables['IWmessages_column'];
        $where = "$c[del_msg_to]='1' AND $c[del_msg_from]='1'";
        if (!DBUtil::deleteWhere('IWmessages', $where)) {
            return LogUtil::registerError($this->__('Error! Sorry! Deletion attempt failed.'));
        }
        $folder = ModUtil::getVar('IWmessages', 'uploadFolder');
        for ($i = 1; $i < 4; $i++) {
            // if the file is not called in other messages delete it from the server
            if ($item['file' . $i] != '') {
                $where = "MD5(" . $c['file1'] . ") = '" . md5($item['file' . $i]) . "' OR MD5(" . $c['file2'] . ") = '" . md5($item['file' . $i]) . "' OR MD5(" . $c['file3'] . ") = '" . md5($item['file' . $i]) . "'";
                // get the objects from the db
                $items = DBUtil::selectObjectArray('IWmessages', $where);
                // Check for an error with the database code, and if so set an appropriate
                // error message and return
                if ($items === false) {
                    return LogUtil::registerError($this->__('Error! Could not load items.'));
                }
                if (count($items) == 0) {
                    //Delete de file from the server
                    $fileName = md5($item['file' . $i] . $item['from_userid']);
                    $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
                    $delete = ModUtil::func('IWmain', 'user', 'deleteFile', array('sv' => $sv,
                                'folder' => $folder,
                                'fileName' => $fileName));
                }
            }
        }
        $sv = ModUtil::func('IWmain', 'user', 'genSecurityValue');
        ModUtil::func('IWmain', 'user', 'userSetVar', array('module' => 'IWmain_block_news',
            'name' => 'have_news',
            'value' => 'me',
            'sv' => $sv));
        //succesfull
        return true;
    }
Exemple #20
0
    /**
     * Esborra el registre impunitId especificat a la taula d'unitats implicades/temàtiques
     * @params $impunitId id del registre de la taula unitatsImplicades
     * @params $uniId id de la unitat per verificar permisos i calcular la URL de retorn
     * @return pàgina de temàtiques
     */
    public function deleteImpunit(){
        $impunitId = FormUtil::getPassedValue('impunitId', null, 'GET');
        $uniId = FormUtil::getPassedValue('uniId', null, 'GET');

        if (ModUtil::apiFunc($this->name, 'user', 'haveAccess', array('accio' => 'new', 'id' => $uniId))) {
            $where = 'impunitId =' . $impunitId;
            DBUtil::deleteWhere('cataleg_unitatsImplicades', $where);
            return system::redirect(ModUtil::url($this->name, 'user', 'tematiques', array('uniId' => $uniId)));  
        }
    }
Exemple #21
0
 /**
  * Uninstall Reviews.
  *
  * @return boolean True on success, false otherwise.
  */
 public function uninstall()
 {
     // delete stored object workflows
     $result = Zikula_Workflow_Util::deleteWorkflowsForModule($this->getName());
     if ($result === false) {
         return LogUtil::registerError($this->__f('An error was encountered while removing stored object workflows for the %s extension.', array($this->getName())));
     }
     try {
         DoctrineHelper::dropSchema($this->entityManager, $this->listEntityClasses());
     } catch (\Exception $e) {
         if (System::isDevelopmentMode()) {
             return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
         }
         return LogUtil::registerError($this->__f('An error was encountered while dropping tables for the %s extension.', array($this->name)));
     }
     // unregister persistent event handlers
     EventUtil::unregisterPersistentModuleHandlers($this->name);
     // unregister hook subscriber bundles
     HookUtil::unregisterSubscriberBundles($this->version->getHookSubscriberBundles());
     // remove all module vars
     $this->delVars();
     // remove category registry entries
     ModUtil::dbInfoLoad('Categories');
     DBUtil::deleteWhere('categories_registry', 'modname = \'' . $this->name . '\'');
     // remove all thumbnails
     $manager = $this->getServiceManager()->getService('systemplugin.imagine.manager');
     $manager->setModule($this->name);
     $manager->cleanupModuleThumbs();
     // remind user about upload folders not being deleted
     $uploadPath = FileUtil::getDataDirectory() . '/' . $this->name . '/';
     LogUtil::registerStatus($this->__f('The upload directories at [%s] can be removed manually.', $uploadPath));
     // uninstallation successful
     return true;
 }
Exemple #22
0
/**
 * Keywords update
 */
function mediashare_editapi_updateKeywords($args)
{
    $dom = ZLanguage::getModuleDomain('mediashare');
    $itemId = (int) $args['itemId'];
    $type = DataUtil::formatForStore($args['type']);
    $keywords = mediashareStripKeywords($args['keywords']);
    $pntable = pnDBGetTables();
    $keywordsColumn = $pntable['mediashare_keywords_column'];
    // First remove existing keywords
    $where = "{$keywordsColumn['itemId']} = '{$itemId}' AND {$keywordsColumn['type']} = '{$type}'";
    $result = DBUtil::deleteWhere('mediashare_keywords', $where);
    if ($result === false) {
        return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('editapi.updateKeywords', 'Could not update the keywords.'), $dom));
    }
    // Split keywords string into keywords array
    $keywordsArray = preg_split('/[\\s,]+/', $keywords);
    // Insert new keywords
    $keywordsArray = array_filter($keywordsArray);
    // strip empty keywords
    foreach ($keywordsArray as $keyword) {
        $keyword = array('itemId' => $itemId, 'type' => $type, 'keyword' => $keyword);
        $keyword = DBUtil::insertObject($keyword, 'mediashare_keywords', 'itemId');
        if ($keyword === false) {
            return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('editapi.updateKeywords', 'Could not insert the keywords.'), $dom));
        }
    }
    return true;
}
Exemple #23
0
 /**
  * Unregister a hook function.
  *
  * @param string $hookobject The hook object.
  * @param string $hookaction The hook action.
  * @param string $hookarea   The area of the hook (either 'GUI' or 'API').
  * @param string $hookmodule Name of the hook module.
  * @param string $hooktype   Name of the hook type.
  * @param string $hookfunc   Name of the hook function.
  *
  * @deprecated since 1.3.0
  *
  * @return boolean True if successful, false otherwise.
  */
 public static function unregisterHook($hookobject, $hookaction, $hookarea, $hookmodule, $hooktype, $hookfunc)
 {
     // define input, all numbers and booleans to strings
     $hookmodule = isset($hookmodule) ? (string) $hookmodule : '';
     // validate
     if (!System::varValidate($hookmodule, 'mod')) {
         return false;
     }
     // Get database info
     $tables = DBUtil::getTables();
     $hookscolumn = $tables['hooks_column'];
     // Remove hook
     $where = "WHERE {$hookscolumn['object']} = '" . DataUtil::formatForStore($hookobject) . "'\n                    AND {$hookscolumn['action']} = '" . DataUtil::formatForStore($hookaction) . "'\n                    AND {$hookscolumn['tarea']} = '" . DataUtil::formatForStore($hookarea) . "'\n                    AND {$hookscolumn['tmodule']} = '" . DataUtil::formatForStore($hookmodule) . "'\n                    AND {$hookscolumn['ttype']} = '" . DataUtil::formatForStore($hooktype) . "'\n                    AND {$hookscolumn['tfunc']} = '" . DataUtil::formatForStore($hookfunc) . "'";
     return (bool) DBUtil::deleteWhere('hooks', $where);
 }
Exemple #24
0
    /**
     * Delete all the sessions about the assignament
     * @author:     Albert Pérez Monfort (aperezm@xtec.cat)
     * @param:	args   Id of the assignament
     * @return:	true if user exists and false otherwise
     */
    public function delSessions($args) {
        $jid = FormUtil::getPassedValue('jid', isset($args['jid']) ? $args['jid'] : null, 'POST');

        // Security check
        if (!SecurityUtil::checkPermission('IWjclic::', "::", ACCESS_ADD)) {
            throw new Zikula_Exception_Forbidden();
        }

        //get jclic activity
        $jclic = ModUtil::apiFunc('IWjclic', 'user', 'get', array('jid' => $jid));
        if ($jclic == false) {
            return LogUtil::registerError($this->__('Could not find the allocation requested'));
        }

        //Check if user can edit the activity because he/she is the owner or only change the expanded/collapsed status
        if ($jclic['user'] != UserUtil::getVar('uid')) {
            return LogUtil::registerError($this->__('You do not have access to edit the activity'));
        }

        //Delete all the activities for the session
        $sessions = ModUtil::apiFunc('IWjclic', 'user', 'getAllSessions', array('jid' => $jid));

        $pntables = DBUtil::getTables();
        $c = $pntables['IWjclic_activities_column'];

        foreach ($sessions as $session) {
            $where = "$c[session_id]='" . $session['session_id'] . "'";
            if (!DBUtil::deleteWhere('IWjclic_activities', $where)) {
                return LogUtil::registerError($this->__('Error! Sorry! Deletion attempt failed.'));
            }
        }

        $c = $pntables['IWjclic_sessions_column'];

        $where = "$c[jclicid]=$jid";
        if (!DBUtil::deleteWhere('IWjclic_sessions', $where)) {
            return LogUtil::registerError($this->__('Error! Sorry! Deletion attempt failed.'));
        }

        return true;
    }
Exemple #25
0
 public function getLocks($args)
 {
     $lockName = $args['lockName'];
     $sessionId = array_key_exists('sessionId', $args) ? $args['sessionId'] : session_id();
     $this->_pageLockRequireAccess();
     $dbtable = DBUtil::getTables();
     $pageLockColumn =& $dbtable['pagelock_column'];
     $now = time();
     $where = "{$pageLockColumn['expiresDate']} < '" . DateUtil::getDatetime($now) . "'";
     DBUtil::deleteWhere('pagelock', $where);
     $where = "{$pageLockColumn['name']} = '" . DataUtil::formatForStore($lockName) . "' AND {$pageLockColumn['lockedBySessionId']} != '" . DataUtil::formatForStore($sessionId) . "'";
     $locks = DBUtil::selectObjectArray('pagelock', $where);
     $this->_pageLockReleaseAccess();
     return $locks;
 }
Exemple #26
0
    public function deltema($args) {
        
        //$ftid = FormUtil::getPassedValue('ftid', isset($args['ftid']) ? $args['ftid'] : null, 'POST');
        //$fid = FormUtil::getPassedValue('fid', isset($args['fid']) ? $args['fid'] : null, 'POST');
        $fid = $this->request->getPost()->get('fid', '');
        $ftid = $this->request->getPost()->get('ftid', '');
        //$ftid = isset($args['ftid']) ? $args['ftid'] : null;
        //$fid = isset($args['fid']) ? $args['fid'] : null;
        $force = isset($args['force']) ? $args['force'] : false;
        // Security check
        if (!SecurityUtil::checkPermission('IWforums::', '::', ACCESS_READ)) {
            return LogUtil::registerPermissionError();
        }
        // Arguments check
        if (!isset($ftid) || !isset($fid)) {
            return LogUtil::registerError("Function deltema: ".$this->__('Error! Could not do what you wanted. Please check your input.'));
        }
        //Cridem la funcié get que retorna les dades
        $link = ModUtil::apiFunc('IWforums', 'user', 'get_tema', array('ftid' => $ftid,
                    'fid' => $fid));
        //Comprovem que el registre efectivament existeix i, per tant, es podrà esborrar
        if ($link == false) {
            return LogUtil::registerError($this->__('No messages have been found'));
        }
        //check if user can access the forum
        if (is_null($fid)) {
            $topic = DBUtil::selectObjectByID('IWforums_temes', $ftid, 'ftid');
            $fid = $topic['fid'];
        }
        $access = ModUtil::func('IWforums', 'user', 'access', array('fid' => $fid));
        if (($access < 4) && (!$force)) {
            return LogUtil::registerError($this->__('You can\'t access the forum'));
        }
        $pntable = DBUtil::getTables();
        $t = $pntable['IWforums_temes'];
        $c = $pntable['IWforums_temes_column'];
        $t2 = $pntable['IWforums_msg'];
        $c2 = $pntable['IWforums_msg_column'];
         
        
        //get messages files
        //$files = ModUtil::apiFunc('IWforums', 'user', 'get_adjunts', array('fid' => $fid));
        $files = ModUtil::apiFunc('IWforums', 'user', 'get_adjunts', array('ftid' => $ftid, 'mode' => 't'));

        //delete messages files
        foreach ($files as $file) {
            //if (false){
            $filePath = ModUtil::getVar('IWmain', 'documentRoot') . '/' . ModUtil::getVar('IWforums', 'urladjunts') . '/' . $file['adjunt'];
            if (file_exists($filePath))
                unlink($filePath);
            //}
        }
        // Messages deletion
        $where = "$c2[ftid]=$ftid";
        if (!DBUtil::deleteWhere('IWforums_msg', $where)) {
            return LogUtil::registerError($this->__('An error has occurred while deleting the message'));
        }
        // record deletion
        if (!DBUtil::deleteWhere('IWforums_temes', $where)) {
            return LogUtil::registerError($this->__('An error has occurred while deleting the message'));
        }

        //Retornem true ja que el procés ha finalitzat amb éxit
        return true;
    }
Exemple #27
0
    /**
     * Perform the search.
     *
     * @param string $args['g']           query string to search
     * @param bool   $args['firstPage']   is this first search attempt? is so - basic search is performed
     * @param string $args['searchtype']  (optional) search type (default='AND')
     * @param string $args['searchorder'] (optional) search order (default='newest')
     * @param int    $args['numlimit']    (optional) number of items to return (default value based on Search settings, -1 for no limit)
     * @param int    $args['page']        (optional) page number (default=1)
     * @param array  $args['active']      (optional) array of search plugins to search (if empty all plugins are used)
     * @param array  $args['modvar']      (optional) array with extrainfo for search plugins
     *
     * @return array array of items array and result count, or false on failure
     */
    public function search($args)
    {
        // query string and firstPage params are required
        if (!isset($args['q']) || empty($args['q']) || !isset($args['firstPage'])) {
            return LogUtil::registerArgsError();
        }
        $vars = array();
        $vars['q'] = $args['q'];
        $vars['searchtype'] = isset($args['searchtype']) && !empty($args['searchtype']) ? $args['searchtype'] : 'AND';
        $vars['searchorder'] = isset($args['searchorder']) && !empty($args['searchorder']) ? $args['searchorder'] : 'newest';
        $vars['numlimit'] = isset($args['numlimit']) && !empty($args['numlimit']) ? $args['numlimit'] : $this->getVar('itemsperpage', 25);
        $vars['page'] = isset($args['page']) && !empty($args['page']) ? (int)$args['page'] : 1;

        $firstPage = isset($args['firstPage']) ? $args['firstPage'] : false;

        $active = isset($args['active']) && is_array($args['active']) && !empty($args['active']) ? $args['active'] : array();
        $modvar = isset($args['modvar']) && is_array($args['modvar']) && !empty($args['modvar']) ? $args['modvar'] : array();

        // work out row index from page number
        $vars['startnum'] = $vars['numlimit'] > 0 ? (($vars['page'] - 1) * $vars['numlimit']) + 1 : 1;

        // Load database stuff
        ModUtil::dbInfoLoad('Search');
        $dbtable = DBUtil::getTables();
        $userId = (int)UserUtil::getVar('uid');
        $searchTable = $dbtable['search_result'];
        $searchColumn = $dbtable['search_result_column'];

        // Create restriction on result table (so user only sees own results)
        $userResultWhere = "$searchColumn[session] = '" . session_id() . "'";

        // Do all the heavy database stuff on the first page only
        if ($firstPage) {
            // Clear current search result for current user - before showing the first page
            // Clear also older searches from other users.
            $dbDriverName = strtolower(Doctrine_Manager::getInstance()->getCurrentConnection()->getDriverName());
            $where = $userResultWhere;
            if ($dbDriverName == 'pgsql') {
                $where .= " OR $searchColumn[found] + INTERVAL '8 HOUR' < NOW()";
            } else {
                $where .= " OR DATE_ADD($searchColumn[found], INTERVAL 8 HOUR) < NOW()";
            }

            DBUtil::deleteWhere('search_result', $where);

            // get all the search plugins
            $search_modules = ModUtil::apiFunc('Search', 'user', 'getallplugins');

            // Ask active modules to find their items and put them into $searchTable for the current user
            // At the same time convert modules list from numeric index to modname index

            $searchModulesByName = array();
            foreach ($search_modules as $mod) {
                // check we've a valid search plugin
                if (isset($mod['functions']) && (empty($active) || isset($active[$mod['title']]))) {
                    foreach ($mod['functions'] as $contenttype => $function) {
                        if (isset($modvar[$mod['title']])) {
                            $param = array_merge($vars, $modvar[$mod['title']]);
                        } else {
                            $param = $vars;
                        }
                        $searchModulesByName[$mod['name']] = $mod;
                        $ok = ModUtil::apiFunc($mod['title'], 'search', $function, $param);
                        if (!$ok) {
                            LogUtil::registerError($this->__f('Error! \'%1$s\' module returned false in search function \'%2$s\'.', array($mod['title'], $function)));

                            return System::redirect(ModUtil::url('Search', 'user', 'main'));
                        }
                    }
                }
            }

            // Count number of found results
            $resultCount = DBUtil::selectObjectCount('search_result', $userResultWhere);
            SessionUtil::setVar('searchResultCount', $resultCount);
            SessionUtil::setVar('searchModulesByName', $searchModulesByName);
        } else {
            $resultCount = SessionUtil::getVar('searchResultCount');
            $searchModulesByName = SessionUtil::getVar('searchModulesByName');
        }

        // Fetch search result - do sorting and paging in database
        // Figure out what to sort by
        switch ($args['searchorder']) {
            case 'alphabetical':
                $sort = 'title';
                break;
            case 'oldest':
                $sort = 'created';
                break;
            case 'newest':
                $sort = 'created DESC';
                break;
            default:
                $sort = 'title';
                break;
        }

        // Get next N results from the current user's result set
        // The "checker" object is used to:
        // 1) do secondary access control (deprecated more or less)
        // 2) let the modules add "url" to the found (and viewed) items
        $checker = new search_result_checker($searchModulesByName);
        $sqlResult = DBUtil::selectObjectArrayFilter('search_result', $userResultWhere, $sort,
                        $vars['startnum'] - 1, $vars['numlimit'], '',
                        $checker, null);
        // add displayname of modules found
        $cnt = count($sqlResult);
        for ($i = 0; $i < $cnt; $i++) {
            $modinfo = ModUtil::getInfoFromName($sqlResult[$i]['module']);
            $sqlResult[$i]['displayname'] = $modinfo['displayname'];
        }

        $result = array(
                'resultCount' => $resultCount,
                'sqlResult' => $sqlResult
        );

        return $result;
    }
Exemple #28
0
 public function deleteTranslation($args)
 {
     $contentId = (int) $args['contentId'];
     $language = isset($args['language']) ? $args['language'] : null;
     $includeHistory = isset($args['includeHistory']) ? $args['includeHistory'] : true;
     $translatedData = array('contentId' => $contentId);
     if ($language !== null) {
         $translatedData['language'] = $language;
     }
     DBUtil::deleteObject($translatedData, 'content_translatedcontent', '', 'contentId');
     $searchableLanguage = $language !== null ? $language : ZLanguage::getLanguageCode();
     $dbtables = DBUtil::getTables();
     $contentSearchColumn = $dbtables['content_searchable_column'];
     $where = $contentSearchColumn['contentId'] . ' = ' . $contentId . ' AND ' . $contentSearchColumn['language'] . ' = \'' . DataUtil::formatForStore($searchableLanguage) . '\'';
     DBUtil::deleteWhere('content_searchable', $where);
     // Get content to find page ID
     if ($includeHistory) {
         $content = $this->getContent(array('id' => $contentId));
         if ($content === false) {
             return false;
         }
         $ok = ModUtil::apiFunc('Content', 'History', 'addPageVersion', array('pageId' => $content['pageId'], 'action' => '_CONTENT_HISTORYTRANSLATIONDEL'));
         if ($ok === false) {
             return false;
         }
     }
     Content_Util::clearCache();
     return true;
 }
Exemple #29
0
 /**
  * delete module
  */
 public function uninstall()
 {
     DBUtil::dropTable('categories_category');
     DBUtil::dropTable('categories_mapobj');
     DBUtil::dropTable('categories_mapmeta');
     DBUtil::dropTable('categories_registry');
     $this->delVars();
     // delete other modules use of categories flag
     $dbtable = DBUtil::getTables();
     $cols = $dbtable['module_vars_column'];
     $name = DataUtil::formatForStore('enablecategorization');
     $where = "{$cols['name']}='{$name}'";
     $res = (bool) DBUtil::deleteWhere('module_vars', $where);
     // Deletion successful
     return true;
 }
Exemple #30
0
    /**
     * Delete a dynamic user data item.
     * 
     * Parameters passed in the $args array:
     * -------------------------------------
     * int dudid ID of the item to delete.
     * 
     * @param array $args All parameters passed to this function.
     * 
     * @return bool true on success, false on failure
     */
    public function delete($args)
    {
        // Argument check
        if (!isset($args['dudid']) || !is_numeric($args['dudid'])) {
            return LogUtil::registerArgsError();
        }

        $dudid = $args['dudid'];
        unset($args);

        // The user API function is called.
        $item = ModUtil::apiFunc('Profile', 'user', 'get', array('propid' => $dudid));

        if ($item == false) {
            return LogUtil::registerError($this->__('Error! No such personal info item found.'));
        }

        // normal type validation
        if ((int)$item['prop_dtype'] != 1) {
            return LogUtil::registerError($this->__('Error! You cannot delete this personal info item.'), 404);
        }

        // Security check
        if (!SecurityUtil::checkPermission('Profile::Item', "$item[prop_label]::$dudid", ACCESS_DELETE)) {
            return LogUtil::registerPermissionError();
        }

        // delete the property data aka attributes
        $dbtables = DBUtil::getTables();
        $objattr_column = $dbtables['objectdata_attributes_column'];

        $delwhere = "WHERE $objattr_column[attribute_name] = '" . DataUtil::formatForStore($item['prop_attribute_name']) . "'
                   AND $objattr_column[object_type] = 'users'";

        $res = DBUtil::deleteWhere('objectdata_attributes', $delwhere);
        if (!$res) {
            return LogUtil::registerError($this->__('Error! Could not delete the personal info item.'));
        }

        // delete the property
        $res = DBUtil::deleteObjectByID('user_property', $dudid, 'prop_id');
        if (!$res) {
            return LogUtil::registerError($this->__('Error! Could not delete the personal info item.'));
        }

        // Let the calling process know that we have finished successfully
        return true;
    }