How to make query in Yii 2 - php

I want to make a code user id with my style, but i confuse to make it in Yii 2.
Can you help me, how write the query like this code below in Yii 2.
This is my code:
$sql = "select * from `$tbadmin` order by `kode_admin` desc";
$q = mysql_query($sql);
$jum = mysql_num_rows($q);
$kd = "ADM";
if ($jum > 0) {
$d = mysql_fetch_array($q);
$idmax = $d["kode_admin"];
$urut = substr($idmax, 3, 2) + 1; //01
if ($urut < 10) {
$idmax = "$kd" . "0" . $urut;
} else {
$idmax = "$kd" . $urut;
}
} else {
$idmax = "$kd" . "01";
}
$kode_admin = $idmax;

$model = Admin::find()->orderBy(['kode_admin DESC'])->all();
foreach($model as $m) {
$m->kode_admin = $this->createKode();
$m->save();
}
Admin is the model for tbadmin table, and createKode could be a function in your controller.
If your are creating a new Admin:
$model = new Admin();
$model->kode_admin = $this->createKode();
$model->save();

$model = AdminModelName::find()->orderBy('kode_admin DESC')->asArray()->all();
foreach($model as $m) {
$m->kode_admin = $this->createKode();
$m->save();
}

create model with Gii Tools
$model = \app\models\tbadmin::find()
->select()
->orderby(['kode_admin => SORT_DESC',])
->all();

Related

PHP experience system // simple

As a begginer in php programming language i'm playing with the code, working on localhost and i did some little projects.Now i am trying to do an experience system as simple as i can, i am stuck at this part and i don't know what i am doing wrong.Some suggestions?
What i am doing wrong?
The code.
function update_user_xp($user_id, $xp_ammount){
global $db;
$params = array('user_id' => $user_id);
$users = $db->rawQuery("SELECT * FROM users_xp WHERE user_id = ?", $params);
$data = array(
'user_xp_amount' => $xp_ammount + $users[0]['user_xp_amount'],
'user_id' => $user_id
);
$db->where ('user_id', $data['user_id']);
if ($db->update ('users_xp', $data)){
$xpReceived = 'You have received '.$xp_ammount.' points of experience! Have a total of '.$data['user_xp_amount'].' points of experience.';
} else {
$xpReceived = $db->getLastError();
}
return $xpReceived;
}
//update_user_xp(4, 10); // user_id: 4, update with 10 points
function get_user_xp ($user_id){
global $db;
$params = array('user_id' => $user_id);
$user = $db->rawQueryOne ('SELECT * FROM users_xp WHERE user_id=?', $params);
$xp = $user['user_xp_amount'];
return $xp;
}
function xp_need () {
global $db;
$xpBarNeed = $db->rawQuery("SELECT `level`, `expneeded` FROM `experience_level`");
foreach ($xpBarNeed as $key => $value) {
$output[] = $value;
}
return $output;
}
$xpn = xp_need();
$userXP = get_user_xp(4);
for($i = 0; $i < count($xpn); $i++){
if($xpn[$i]['expneeded'] == $userXP)
{
//This part is working well
print 'You are level <b>' . $xpn[$i]['level'].'</b>';
} else {
if ($userXP > $xpn[$i]['expneeded'] && $userXP >= $xpn[$i]['expneeded'])
{
//This is the part that doesn t work,
$diffEXP = $xpn[$i]['expneeded'] -= $userXP;
print 'You need more exp '. $diffEXP.'</br>';
}
}
}
This is how i am seeing in the page.
https://prnt.sc/u7z18u
Please note that my solution is not the best or say a well-optimized solution at the time of writing. I will try to optimize it in the near future. For the time being, you can use this:
<?php
$xpn = xp_need();
$userXP = get_user_xp(4);
$level = 0;
$nextExp = 0;
for ($i = count($xpn) - 1;$i >= 0;$i--)
{
if ($userXP >= $xpn[$i]['expneeded'])
{
$level = $xpn[$i]['level'];
$nextExp = $xpn[$i + 1]['expneeded'];
break;
}
}
$expNeeded = $nextExp - $userXP;
$percentage = round(($userXP/$nextExp) * 100);
echo "Current level: " . $level;
echo "<br/>Exp needed for the next level (" . ($level + 1) . "): " . $expNeeded;
echo "<br/>Exp achieved percentage for the next level: " . $percentage;
?>

Unset Designer from variable

I am displaying product Id, product name , designer, but i need to hide "designer".
so i am trying to unset designer from variable $orderitems, i am trying below code, but still Designer column displaying
i am fetching product id , name , Designer from this code : ->addAttributeToSelect('dproduct_id') & trying this code to unset : unset($orderitems['designer_id'])
function getDesignerCollection()
{
$user_home = new USER();
$stmts = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmts->execute(array(
":uid" => $_SESSION['userSession']
));
$rows = $stmts->fetch(PDO::FETCH_ASSOC);
$accountType = $rows['type'];
if ($accountType == "admin")
{
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('designer_id', array(
'nin' => '0'
));
}
else
{
$order = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('designer_id', array(
'like' => '%' . $_SESSION['userSession'] . '%'
))
->addAttributeToSelect('dproduct_id')
->addAttributeToSelect('state');
//unset($orderitems['designer_id']);
}
$i = 0;
foreach($order as $orderData)
{
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
$k = 0;
$oDate = new DateTime($orderData['created_at']);
$sDate = $oDate->format("Y-m-d");
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details WHERE designerorder_id=:designerorder_id");
$stmtorders->execute(array(
":designerorder_id" => $orderData['entity_id']
));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
$productdetail = Mage::getModel('catalog/product')->load($orderitemsarray[$k]);
$designerName = getDesignerName($productdetail->getDesignerID()) . " -(" . $productdetail->getDesignerID() . ")";
$responce[] = array(
$orderData->getIncrementId() ,
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$productdetail->getName() ,
$designerName,
$orderData['status'],
$orderData['grand_total'],
$orderData['customer_email'],
$commission,
$dorderStatus,
$sDate
);
}
$k++;
$i++;
}
}
echo json_encode($responce);
unset($orderitems['designer_id']);
}
Note : I really tried lot before posting here, i am new to php.

modify a query of a joomla module

i have a module which executes two functions. the first filters and showsthe latest comments per category. the second one filters and shows the top commenters of all categories. i want to hack it in order to show the top commenters per category. for the first one there is in the backend the option to select category but for the top commenters there is not.
here is the code of the module. forgive me for its length.
class modK2CommentsHelper
{
public static function getLatestComments(&$params)
{
$mainframe = JFactory::getApplication();
$limit = $params->get('comments_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$cid = $params->get('category_id', NULL);
$jnow = JFactory::getDate();
$now = K2_JVERSION != '15' ? $jnow->toSql() : $jnow->toMySQL();
$nullDate = $db->getNullDate();
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
$query = "SELECT c.*, i.catid, i.title, i.alias, category.alias as catalias, category.name as categoryname
FROM #__k2_comments as c
LEFT JOIN #__k2_items as i ON i.id=c.itemID
LEFT JOIN #__k2_categories as category ON category.id=i.catid
WHERE i.published=1
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND i.access<={$aid} ";
}
$query .= " AND category.published=1 AND category.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND category.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND category.access<={$aid} ";
}
$query .= " AND c.published=1 ";
if ($params->get('catfilter'))
{
if (!is_null($cid))
{
if (is_array($cid))
{
JArrayHelper::toInteger($cid);
$query .= " AND i.catid IN(".implode(',', $cid).")";
}
else
{
$query .= " AND i.catid=".(int)$cid;
}
}
}
if (K2_JVERSION != '15')
{
if ($mainframe->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND category.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
}
$query .= " ORDER BY c.commentDate DESC ";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
if (count($rows))
{
foreach ($rows as $row)
{
if ($params->get('commentDateFormat') == 'relative')
{
$config = JFactory::getConfig();
$now = new JDate();
if (K2_JVERSION == '30')
{
$tzoffset = new DateTimeZone(JFactory::getApplication()->getCfg('offset'));
$now->setTimezone($tzoffset);
}
else
{
$tzoffset = $config->getValue('config.offset');
$now->setOffset($tzoffset);
}
$created = new JDate($row->commentDate);
$diff = $now->toUnix() - $created->toUnix();
$dayDiff = floor($diff / 86400);
if ($dayDiff == 0)
{
if ($diff < 5)
{
$row->commentDate = JText::_('K2_JUST_NOW');
}
elseif ($diff < 60)
{
$row->commentDate = $diff.' '.JText::_('K2_SECONDS_AGO');
}
elseif ($diff < 120)
{
$row->commentDate = JText::_('K2_1_MINUTE_AGO');
}
elseif ($diff < 3600)
{
$row->commentDate = floor($diff / 60).' '.JText::_('K2_MINUTES_AGO');
}
elseif ($diff < 7200)
{
$row->commentDate = JText::_('K2_1_HOUR_AGO');
}
elseif ($diff < 86400)
{
$row->commentDate = floor($diff / 3600).' '.JText::_('K2_HOURS_AGO');
}
}
}
$row->commentText = K2HelperUtilities::wordLimit($row->commentText, $params->get('comments_word_limit'));
$row->commentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->commentText);
$row->itemLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($row->itemID.':'.urlencode($row->alias), $row->catid.':'.urlencode($row->catalias))));
$row->link = $row->itemLink."#comment{$row->id}";
$row->catLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($row->catid.':'.urlencode($row->catalias))));
if ($row->userID > 0)
{
$row->userLink = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
$getExistingUser = JFactory::getUser($row->userID);
$row->userUsername = $getExistingUser->username;
}
else
{
$row->userUsername = $row->userName;
}
// Switch between commenter name and username
if ($params->get('commenterName', 1) == 2)
$row->userName = $row->userUsername;
$row->userImage = '';
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
$comments[] = $row;
}
return $comments;
}
}
public static function getTopCommenters(&$params)
{
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
$limit = $params->get('commenters_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$query = "SELECT COUNT(id) as counter, userName, userID, commentEmail FROM #__k2_comments WHERE userID > 0 AND published = 1 GROUP BY userID ORDER BY counter DESC";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
if (count($rows))
{
foreach ($rows as $row)
{
if ($row->counter > 0)
{
$row->link = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
if ($params->get('commenterNameOrUsername', 1) == 2)
{
$getExistingUser = JFactory::getUser($row->userID);
$row->userName = $getExistingUser->username;
}
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
if ($params->get('commenterLatestComment'))
{
$query = "SELECT * FROM #__k2_comments WHERE userID = ".(int)$row->userID." AND published = 1 ORDER BY commentDate DESC";
$db->setQuery($query, 0, 1);
$comment = $db->loadObject();
$item = JTable::getInstance('K2Item', 'Table');
$item->load($comment->itemID);
$category = JTable::getInstance('K2Category', 'Table');
$category->load($item->catid);
$row->latestCommentText = $comment->commentText;
$row->latestCommentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->latestCommentText);
$row->latestCommentLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($category->alias))))."#comment{$comment->id}";
$row->latestCommentDate = $comment->commentDate;
}
$commenters[] = $row;
}
}
if (isset($commenters))
return $commenters;
}
}
}
every help is appreciated. thank you very much

Previous/next button in PHP

I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!

How to handle Exception when Zend_Acl is On? it gives Resource 'default::error::error' not found'

i've implemeted the Zend_Acl and its seems to be working.my resources are links :
module_name . "::" . controller_name . "::" . action_name;
i've added something in my code that's breaking and it seems that's i'm redirected to the usual error page but that the Acl comes in saying
Fatal error: Uncaught exception 'Zend_Acl_Exception' with message 'Resource 'default::error::error' not found' in F:\work\php\zendworkspace\myproject\library\Zend\Acl.php on line 365
i have added the default::error::error to the resources but the error is still the same.
when i remove the code that's breaking the whole thing works again.
So i would definitely have the same error when something breaks in my code.
I would like to find out how to solve this. thanks for reading and sharing your experience.
Edit:
the code to implement that is kind of long. this is a db driven ACL with doctrine.
i've modified this tutorial to implement mine.i've cut out the myACL class, looks the same as the one in the tutorial, and the ACL plugin is kind of the same.i've registerd it in the application.ini.
// this class build all the roles and resouces and add 2 users to 2 differents roles and so on
class CMS_Util_AddResourcesAndRoles {
private $arrModules = array();
private $arrControllers = array();
public $arrActions = array();
private $arrIgnores = array('.', '..', '.svn');
public function BuildMCAArrays() {
$this->BuildModuleArray();
$this->BuildControllersArray();
$this->BuildActionArray();
return $this;
}
public function CheckData() {
if (count($this->arrModules) < 1)
throw new CMS_Exception_ResourceNotFound("No Modules found ..");
if (count($this->arrControllers) < 1)
throw new CMS_Exception_ResourceNotFound("No Controllers found ..");
if (count($this->arrActions) < 1)
throw new CMS_Exception_ResourceNotFound("No Actions found ..");
}
public function BuildModuleArray() {
$cmsApplicationModules = opendir(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'modules');
while (false !== ($cmsFile = readdir($cmsApplicationModules))) {
if (!in_array($cmsFile, $this->arrIgnores)) {
if (is_dir(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $cmsFile)) {
$this->arrModules[] = $cmsFile;
}
}
}
closedir($cmsApplicationModules);
return $this->arrModules;
}
public function BuildControllersArray() {
if (count($this->arrModules) > 0) {
foreach ($this->arrModules as $strModuleName) {
$cmsControllerFolder = opendir(APPLICATION_PATH . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . $strModuleName . DIRECTORY_SEPARATOR . "controllers");
while (false !== ($cmsFile = readdir($cmsControllerFolder))) {
if (!in_array($cmsFile, $this->arrIgnores)) {
if (preg_match('/Controller/', $cmsFile)) {
// if(strtolower(substr($cmsFile, 0, -14)) != "error")
// $this->arrControllers[$strModuleName][] = strtolower(substr($cmsFile, 0, -14));
$this->arrControllers[$strModuleName][] = strtolower (substr($cmsFile, 0, -14));
}
}
}
closedir($cmsControllerFolder);
}
}
return $this->arrControllers;
}
private function BuildActionArray() {
// $arrMethods = array();
if (count($this->arrControllers) > 0) {
foreach ($this->arrControllers as $strModule => $strController) {
foreach ($strController as $strController) {
if ($strModule == "default") {
$strClassName = ucfirst($strController . 'Controller');
} else {
$strClassName = ucfirst($strModule) . '_' . ucfirst($strController . 'Controller');
}
if (!class_exists($strClassName)) {
Zend_Loader::loadFile(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $strModule . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . ucfirst($strController) . 'Controller.php');
}
$objReflection = new Zend_Reflection_Class($strClassName);
$arrMethods = $objReflection->getMethods();
foreach ($arrMethods as $arrMethod) {
if (preg_match('/Action/', $arrMethod->name)) {
$this->arrActions[$strModule][$strController][] = substr($arrMethod->name, 0, -6);
// $this->arrActions[$strModule][$strController][] = substr($this->_camelCaseToHyphens($objMethods->name), 0, -6);
}
}
}
}
}
return $this->arrActions;
}
private function _camelCaseToHyphens($string) {
if ($string == 'currentPermissionsAction') {
$found = true;
}
$length = strlen($string);
$convertedString = '';
for ($i = 0; $i < $length; $i++) {
if (ord($string[$i]) > ord('A') && ord($string[$i]) < ord('Z')) {
$convertedString .= '-' . strtolower($string[$i]);
} else {
$convertedString .= $string[$i];
}
}
return strtolower($convertedString);
}
public function WriteResourcesToDb() {
$this->BuildMCAArrays();
$this->CheckData();
$resources = array();
foreach ($this->arrModules as $strModuleName) {
if (array_key_exists($strModuleName, $this->arrControllers)) {
foreach ($this->arrControllers[$strModuleName] as $strControllerName) {
if (array_key_exists($strControllerName, $this->arrActions[$strModuleName])) {
foreach ($this->arrActions[$strModuleName][$strControllerName] as $strActionName) {
$res = new CMS_Model_Resource();
$res->module_name = $strModuleName;
$res->controller_name = $strControllerName;
$res->action_name = $strActionName;
$res->name = $strModuleName . "_" . $strControllerName . "_" . $strActionName;
$resources[] = $res;
$this->PersistResource($resources);
}
}
}
}
}
return $this;
}
private function PersistResource(array $resourceobject) {
try {
$collection = new Doctrine_Collection("CMS_Model_Resource");
foreach ($resourceobject as $resource) {
$collection->add($resource);
}
$collection->save();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function WriteRoleAndUserstoDb(){
$guest = new CMS_Model_Role();
$guest->name = "guest";
$guest->description = "simple user";
$guest->canbedeleted = true;
$member = new CMS_Model_Role();
$member->name = "member";
$member->description = "member with limited privileges,can access member reserved resources";
$member->canbedeleted = true;
$publisher = new CMS_Model_Role();
$publisher->name = "publisher";
$publisher->description = "publisher with publish an unpublished privileges";
$publisher->canbedeleted = true;
$manager = new CMS_Model_Role();
$manager->name = "manager";
$manager->description = "manager with privileges to publish, to unpublish, general manager of the site";
$manager->canbedeleted = true;
$admin = new CMS_Model_Role();
$admin->name = "administrator";
$admin->description = "admin with all privileges";
$admin->canbedeleted = false;
$superadmin = new CMS_Model_Role();
$superadmin->name = "superadmin";
$superadmin->description = "superadmin to rule them all";
$superadmin->canbedeleted = false;
$superadmin->Parents[0] = $admin;
$admin->Parents[0] = $manager;
$manager->Parents[0] = $publisher;
$publisher->Parents[0] = $member;
$member->Parents[0] = $guest;
$adminname = new CMS_Model_User();
$adminname->id = CMS_Util_Common::uuid();
$adminname->first_name = "adminname";
$adminname->last_name = "surname";
$adminname->full_name = "adminname surname";
$adminname->password = "password";
$adminname->email = "mister#somemail.com";
$adminname->is_active = true;
$adminname->is_verified = true;
$adminname->username ="superadmin";
$adminname->Role = $superadmin;
$adminname2 = new CMS_Model_User();
$adminname2->id = CMS_Util_Common::uuid();
$adminname2->first_name = "adminname2";
$adminname2->last_name = "adminsurname";
$adminname2->email="shallom#someemail.fr";
$adminname2->full_name = "adminname2 adminsurname";
$adminname2->password = "adminadmin";
$adminname2->is_active = true;
$adminname2->is_verified = true;
$adminname2->username ="admin";
$adminname2->Role = $admin;
$thepublisher = new CMS_Model_User();
$thepublisher->id = CMS_Util_Common::uuid();
$thepublisher->first_name = "one publisher";
$thepublisher->last_name = "lastname";
$thepublisher->full_name = "something something";
$thepublisher->email = "user#somegmail.com";
$thepublisher->password = "password";
$thepublisher->username = "publisher";
$thepublisher->is_active = true;
$thepublisher->is_verified = true;
$thepublisher->Role = $publisher;
$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$conn->flush();
return $this;
}
public function AssignResourcesToRoles(){
$guestcollection = new Doctrine_Collection("CMS_Model_RoleResource");
$guestroles = Doctrine_Core::getTable("CMS_Model_Role")->GetRoleByName("guest");
$defautresources = Doctrine_Core::getTable("CMS_Model_Resource")->GetResourceByModule("default");
foreach($defautresources as $resource){
$guestroleresource = new CMS_Model_RoleResource();
$guestroleresource->Role = $guestroles;
$guestroleresource->Resource = $resource;
$guestcollection->add($guestroleresource);
}
$guestcollection->save();
$admincollection = new Doctrine_Collection("CMS_Model_RoleResource");
$adminroles = Doctrine_Core::getTable("CMS_Model_Role")->GetRoleByName("superadmin");
$adminresources = Doctrine_Core::getTable("CMS_Model_Resource")->GetResourceByModule("admin");
foreach($adminresources as $resource){
$adminroleresource = new CMS_Model_RoleResource();
$adminroleresource->Role = $adminroles;
$adminroleresource->Resource = $resource;
$admincollection->add($adminroleresource);
}
$admincollection->save();
return $this;
}
public function SetAclUp(){
$this->WriteResourcesToDb();
$this->WriteRoleAndUserstoDb();
$this->AssignResourcesToRoles();
return $this;
}
}
as you can see i've granted all links under default to role guest meaning guest can see the default::error::error page when there is a problem.
I can also assure you that, when nothing is broken in my code, i can login with the publisher credential and get bounced anytime i'm trying to go to the admin panel.
The most popular error is that you have not added the resource for any instance.

Categories