bash_sync_perms.php 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  1. <?php
  2. /**
  3. * by plabudda 2013-10-09:
  4. *
  5. * 1. install:
  6. * - create *.plist file:
  7. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  8. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  9. * - load by launchctl:
  10. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  11. *
  12. * 2. uninstall:
  13. * - unload from launchctl:
  14. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 3. debug:
  17. * - debug by www:
  18. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  19. * - more verbose debug:
  20. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  21. * - task:
  22. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  23. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  24. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  25. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  26. *
  27. *
  28. * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
  29. * 'WAITING' - Kandydaci
  30. * 'NORMAL' - Aktywni pracownicy
  31. * 'DELETED' - Wyłączone konta
  32. * 'OFF_SOFT' - ?
  33. * 'OFF_HARD' - ?
  34. *
  35. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  36. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  37. #read PASSWORD
  38. #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
  39. #do
  40. #echo mkdir $a
  41. #mkdir $a
  42. #done
  43. *do wywolania w katalogach IN/OUT:
  44. # cd IN
  45. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  46. *
  47. *
  48. *
  49. * DONE: koresp format: PISMA/ID/...
  50. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  51. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  52. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
  53. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  54. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  55. *
  56. *
  57. * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
  58. *
  59. * 5. Sync custom tables
  60. * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
  61. * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
  62. * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
  63. * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
  64. */
  65. ini_set('max_execution_time', 300);
  66. ini_set('memory_limit', '512M');
  67. define('DS', DIRECTORY_SEPARATOR);
  68. define('APP_PATH_ROOT', dirname(__FILE__));
  69. define('APP_PATH_WWW', dirname(__FILE__));
  70. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  71. // set ini to log errors into error log file
  72. ini_set('display_startup_errors', '0');
  73. ini_set('log_errors', '1');
  74. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  75. date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions
  76. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  77. Lib::loadClass('V');
  78. Lib::loadClass('Config');
  79. Lib::loadClass('DB');
  80. Lib::loadClass('User');
  81. Lib::loadClass('FoldersConfig');
  82. Lib::loadClass('FileUploader');
  83. if (isset($_SERVER["argv"][1])) {
  84. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  85. }
  86. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  87. $info = array();
  88. $info['max_execution_time'] = ini_get('max_execution_time');
  89. $info['memory_limit'] = ini_get('memory_limit');
  90. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  91. ini_set('max_execution_time', 300);
  92. ini_set('memory_limit', '512M');
  93. $info = array();
  94. $info['max_execution_time'] = ini_get('max_execution_time');
  95. $info['memory_limit'] = ini_get('memory_limit');
  96. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  97. }
  98. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  99. SyncPerms::run(null, null, 'users', null);
  100. }
  101. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  102. SyncPerms::run(null, null, 'usersAll', null);
  103. }
  104. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  105. SyncPerms::run(null, null, 'nextTask', null);
  106. }
  107. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  108. SyncPerms::run(null, null, 'newFiles', null);
  109. }
  110. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  111. $cmd = " ls -Rlea . ";
  112. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  113. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
  114. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  115. $filesWithPermsTree = array();
  116. $lastName = '';
  117. $folderParent = '';
  118. foreach ($filesWithPerms as $line) {
  119. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  120. $fileParts = array();
  121. $filePartsArr = explode(' ', $line);
  122. $lastInd = 0;
  123. foreach ($filePartsArr as $vPart) {
  124. if ($lastInd > 7) {// file name
  125. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  126. $lastInd++;
  127. }
  128. else if (!empty($vPart) || $vPart === '0') {
  129. $fileParts[] = $vPart;
  130. $lastInd++;
  131. }
  132. }
  133. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  134. $lastName = '..';
  135. continue;
  136. }
  137. $file = new stdClass();
  138. if (!isset($fileParts[8])) {
  139. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  140. //continue;
  141. } else {
  142. // fix file name from bad chars
  143. // [8] => CV_Kowalski Mariusz`.pdf
  144. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  145. // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  146. // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  147. // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
  148. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  149. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  150. }
  151. echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
  152. $file->name = end($fileParts);
  153. $file->path = array();
  154. if ($folderParent) $file->path[] = $folderParent;
  155. $file->path[] = end($fileParts);
  156. $file->path = implode('/', $file->path);
  157. //$file->owner = $fileParts[2];
  158. //$file->group = $fileParts[3];
  159. //$file->perms = $fileParts[0];
  160. $file->isDir = (substr($line, 0, 1) == 'd');
  161. $file->permsExt = array();
  162. $filesWithPermsTree[$file->name] = $file;
  163. $lastName = $file;
  164. }
  165. else if (substr($line, 0, 1) == ' ') {// extended perm line
  166. if ($lastName == '..') {
  167. continue;
  168. }
  169. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  170. }
  171. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  172. $folderParent = substr($line, 2, -1);
  173. }
  174. else if (substr($line, 0, 5) == 'total') {
  175. continue;
  176. }
  177. else if (empty($line)) {
  178. $folderParent = '';
  179. continue;
  180. }
  181. }
  182. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  183. }
  184. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  185. SyncPerms::run(null, null);
  186. }
  187. else {
  188. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  189. }
  190. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  191. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  192. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  193. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  194. }
  195. class SyncPerms {
  196. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  197. if ($arg2 == 'addToLaunchctl') self::task__addToLaunchctl($domain);
  198. else if ($arg2 == 'newFiles') self::task__newFiles();
  199. else if ($arg2 == 'nextTask') self::task__nextTask();
  200. else if ($arg2 == 'testErrorLog') self::task__testErrorLog();
  201. else if ($arg2 == 'users') self::usersAction();
  202. else if ($arg2 == 'usersAll') self::usersAllAction();
  203. else if ($arg2 == 'SyncPermsCustomTables') self::task__SyncPermsCustomTables();
  204. else if ($arg2 == 'sendNotify') self::sendNotify();
  205. else self::task__default();
  206. }
  207. public static function task__addToLaunchctl($domain) {
  208. $plistFile = "/Library/LaunchDaemons/pl.biallnet.sync_perms.{$domain}.php.plist";
  209. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  210. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  211. <plist version=\"1.0\">
  212. <dict>
  213. <key>Disabled</key>
  214. <false/>
  215. <key>Label</key>
  216. <string>pl.biallnet.sync_perms.{$domain}.php</string>
  217. <key>UserName</key>
  218. <string>root</string>
  219. <key>ProgramArguments</key>
  220. <array>
  221. <string>php</string>
  222. <string>{$_SERVER["argv"][0]}</string>
  223. <string>{$_SERVER["argv"][1]}</string>
  224. </array>
  225. <key>StartInterval</key>
  226. <integer>60</integer>
  227. </dict>
  228. </plist>
  229. \" > {$plistFile}");
  230. echo "Run as root: launchctl load {$plistFile} \n";
  231. }
  232. public static function task__newFiles() {
  233. $time = new stdClass();
  234. $time->start = time();
  235. self::newFilesAction();
  236. $time->end = time();
  237. // TODO: print operation time if DBG
  238. }
  239. public static function task__nextTask() {
  240. $time = new stdClass();
  241. $time->start = time();
  242. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  243. self::installTable();
  244. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
  245. self::generateTasksNewRecords();
  246. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
  247. self::generateTasksUpdated();
  248. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
  249. $limit = V::get('_limit', 1, $_GET, 'int');
  250. for ($i = 0; $i < $limit; $i++) {
  251. $time->cur = time();
  252. if ($time->cur - $time->start > 60 * 5) {
  253. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
  254. break;
  255. }
  256. $task = self::nextTaskAction();
  257. if (!$task) break;
  258. }
  259. }
  260. public static function task__testErrorLog() {
  261. echo "display_errors: " . ini_get("display_errors") . "\n";
  262. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  263. echo "log_errors: " . ini_get("log_errors") . "\n";
  264. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  265. echo "error_log: " . ini_get("error_log") . "\n";
  266. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  267. }
  268. public static function task__SyncPermsCustomTables() {
  269. $DBG_TIME = true;
  270. $dbgTime = new stdClass();
  271. $dbgTime->startTime = microtime(true);
  272. $dbgTime->lastTime = $dbgTime->startTime;
  273. $customSync = new SyncPermsCustomTables();
  274. // TODO: $customSync->run();
  275. $customSync->fetchConfig();
  276. if ($DBG_TIME) {
  277. $dbgTime->curTime = microtime(true);
  278. trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  279. $dbgTime->lastTime = $dbgTime->curTime;
  280. }
  281. $customSync->installTable();
  282. if ($DBG_TIME) {
  283. $dbgTime->curTime = microtime(true);
  284. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  285. $dbgTime->lastTime = $dbgTime->curTime;
  286. }
  287. $rowId = (int)$arg3;
  288. if ($rowId > 0) {
  289. $customSync->executeTask('DEALS_TABLE', $rowId);// TODO: DEALS_TABLE ?
  290. }
  291. else {
  292. $customSync->generateTasksNewRecords();
  293. if ($DBG_TIME) {
  294. $dbgTime->curTime = microtime(true);
  295. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  296. $dbgTime->lastTime = $dbgTime->curTime;
  297. }
  298. $customSync->generateTasksUpdated();
  299. if ($DBG_TIME) {
  300. $dbgTime->curTime = microtime(true);
  301. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  302. $dbgTime->lastTime = $dbgTime->curTime;
  303. }
  304. $customSync->newFilesAction();
  305. if ($DBG_TIME) {
  306. $dbgTime->curTime = microtime(true);
  307. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  308. $dbgTime->lastTime = $dbgTime->curTime;
  309. }
  310. $limit = 1000;
  311. for ($i = 0; $i < $limit; $i++) {
  312. $loopTasksFired = 0;
  313. foreach ($customSync->_tbls as $tblName => $tblConf) {
  314. $task = $customSync->nextTaskAction($tblName);
  315. if ($DBG_TIME) {
  316. $dbgTime->curTime = microtime(true);
  317. trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  318. $dbgTime->lastTime = $dbgTime->curTime;
  319. }
  320. if (!$task) {
  321. // TODO: rm $tblName from config to prevent searching for task in next loops
  322. unset($customSync->_tbls[$tblName]);
  323. continue;
  324. }
  325. $loopTasksFired++;
  326. }
  327. if (!$loopTasksFired) {
  328. if ($DBG_TIME) {
  329. $dbgTime->curTime = microtime(true);
  330. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  331. $dbgTime->lastTime = $dbgTime->curTime;
  332. }
  333. break;
  334. }
  335. $i += $loopTasksFired;
  336. }
  337. }
  338. $dbgTime->endTime = microtime(true);
  339. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  340. }
  341. public static function task__default() {
  342. $DBG_TIME = false;
  343. $DBG_MEMORY = false;
  344. $dbgTime = new stdClass();
  345. $dbgTime->start = time();
  346. $dbgTime->startTime = microtime(true);
  347. $dbgTime->lastTime = $dbgTime->startTime;
  348. self::installTable();
  349. if ($DBG_TIME) {
  350. $dbgTime->curTime = microtime(true);
  351. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  352. $dbgTime->lastTime = $dbgTime->curTime;
  353. }
  354. self::generateTasksNewRecords();
  355. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  356. if ($DBG_TIME) {
  357. $dbgTime->curTime = microtime(true);
  358. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  359. $dbgTime->lastTime = $dbgTime->curTime;
  360. }
  361. self::generateTasksUpdated();
  362. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  363. if ($DBG_TIME) {
  364. $dbgTime->curTime = microtime(true);
  365. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  366. $dbgTime->lastTime = $dbgTime->curTime;
  367. }
  368. $dbgTime->cur = time();
  369. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  370. trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  371. return;
  372. }
  373. self::newFilesAction();
  374. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  375. if ($DBG_TIME) {
  376. $dbgTime->curTime = microtime(true);
  377. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  378. $dbgTime->lastTime = $dbgTime->curTime;
  379. }
  380. $limit = 100;
  381. for ($i = 0; $i < $limit; $i++) {
  382. $dbgTime->cur = time();
  383. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  384. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  385. return;
  386. }
  387. $task = self::nextTaskAction();
  388. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  389. if ($DBG_TIME) {
  390. $dbgTime->curTime = microtime(true);
  391. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  392. $dbgTime->lastTime = $dbgTime->curTime;
  393. }
  394. if (!$task) {
  395. $dbgTime->cur = time();
  396. break;
  397. }
  398. }
  399. $customSync = new SyncPermsCustomTables();
  400. $customSync->run();
  401. $dbgTime->cur = time();
  402. $dbgTime->endTime = microtime(true);
  403. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  404. if ($DBG_TIME) {
  405. $dbgTime->curTime = microtime(true);
  406. trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  407. $dbgTime->lastTime = $dbgTime->curTime;
  408. }
  409. self::sendNotify();
  410. Lib::loadClass('Router');
  411. echo "DBG: UrlAction_WmsGenerate->doGenerate() START...\n";
  412. Router::getRoute('UrlAction_WmsGenerate')->doGenerate();
  413. echo "DBG: UrlAction_WmsGenerate->doGenerate() END\n";
  414. echo "DBG: UrlAction_BiAuditGenerate->doGenerate() START...\n";
  415. //Router::getRoute('UrlAction_BiAuditGenerate')->doGenerate();
  416. echo "DBG: UrlAction_BiAuditGenerate->doGenerate() END\n";
  417. }
  418. public static function sendNotify() {
  419. Lib::loadClass('Router');
  420. $cronTaskName = 'sendNotify';
  421. $keyToken = 'bach_sync_perms';
  422. $token = Router::getRoute('Cron')->generateCliAuthToken($keyToken, $cronTaskName, 300 * 10);
  423. echo "DBG: token = '{$token}'" . "\n";
  424. $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
  425. if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
  426. //file_get_contents("https://{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task=sendNotify");
  427. function runUrlTask($url) {
  428. $ch = curl_init();
  429. curl_setopt($ch, CURLOPT_VERBOSE, true);
  430. curl_setopt($ch, CURLOPT_URL, $url);
  431. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  432. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  433. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  434. $return = curl_exec($ch);
  435. curl_close($ch);
  436. return $return;
  437. }
  438. $string = runUrlTask("{$baseUrl}/index.php?_route=Cron&_key={$keyToken}&_token={$token}&_task={$cronTaskName}");
  439. echo "DBG: string -----------------------\n{$string}\nEOF string---------------------------------\n";
  440. }
  441. public static function installTable() {
  442. $db = DB::getDB();
  443. if (!$db) die("DB Error: No DB! L." . __LINE__);
  444. $sql = "
  445. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  446. `ID` int(11) NOT NULL AUTO_INCREMENT,
  447. `ID_PROJECT` int(11) NOT NULL,
  448. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  449. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  450. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  451. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  452. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  453. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  454. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  455. PRIMARY KEY (`ID`),
  456. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  457. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  458. ";
  459. $db->query($sql);
  460. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  461. $db->query($sql);
  462. $sql = "
  463. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  464. FOR EACH ROW BEGIN
  465. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  466. update `_SYNC_FILE_PERMS` as s set
  467. s.`A_SYNCHRONIZED`=0
  468. where
  469. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  470. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  471. END IF;
  472. END
  473. ";
  474. $db->query($sql);
  475. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  476. $db->query($sql);
  477. $sql = "
  478. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  479. FOR EACH ROW BEGIN
  480. IF NEW.`ID_PROJECT` > 0 THEN
  481. update `_SYNC_FILE_PERMS` as s set
  482. s.`A_SYNCHRONIZED`=0
  483. where
  484. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  485. END IF;
  486. END
  487. ";
  488. $db->query($sql);
  489. if (V::get('DBG', '', $_GET, 'int') > 0) {
  490. if ($db->has_errors()) {
  491. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB errors (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
  492. }
  493. }
  494. }
  495. public static function newFilesAction() {
  496. $task = self::getTaskNewFiles();
  497. $taskResult = self::fixLastModifiedFiles($task);
  498. self::saveTask(-1);
  499. }
  500. public static function nextTaskAction() {
  501. $task = self::getTask();
  502. if (!$task) return false;
  503. self::executeTask($task);
  504. /*
  505. if (isset($task->A_SYNC_RESULT->total)
  506. && isset($task->A_SYNC_RESULT->lastDone)
  507. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  508. ) {
  509. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  510. } else {
  511. self::saveTask($task->ID_PROJECT);
  512. }
  513. */
  514. self::saveTask($task->ID_PROJECT);
  515. return $task;
  516. }
  517. public static function generateTasksUpdated() {
  518. $db = DB::getDB();
  519. if (!$db) die("DB Error: No DB! L." . __LINE__);
  520. $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  521. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  522. where
  523. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  524. and (
  525. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  526. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  527. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  528. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  529. )
  530. ";
  531. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  532. set
  533. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  534. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  535. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  536. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  537. , s.`A_SYNCHRONIZED`=0
  538. where
  539. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  540. and (
  541. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  542. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  543. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  544. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  545. )
  546. ";
  547. $res = $db->query($sql);
  548. }
  549. public static function generateTasksNewRecords() {
  550. $db = DB::getDB();
  551. if (!$db) die("DB Error: No DB! L." . __LINE__);
  552. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  553. values (-1, '', '', '', '');
  554. ";
  555. $res = $db->query($sql);
  556. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  557. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  558. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  559. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  560. where p.`A_STATUS`!='DELETED'
  561. ";
  562. $res = $db->query($sql);
  563. }
  564. /**
  565. * Znajdź najstarszy aktualizowany projekt.
  566. */
  567. public static function getTask() {
  568. $task = null;
  569. $db = DB::getDB();
  570. if (!$db) die("DB Error: No DB! L." . __LINE__);
  571. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  572. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
  573. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  574. }
  575. $sql = "select s.*
  576. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  577. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  578. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  579. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  580. , p.`M_DIST_DESC` as p__M_DIST_DESC
  581. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  582. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  583. from `_SYNC_FILE_PERMS` as s
  584. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  585. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  586. where
  587. {$sqlWhereProjID}
  588. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  589. limit 1
  590. ";
  591. $res = $db->query($sql);
  592. if ($r = $db->fetch($res)) {
  593. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  594. $task = $r;
  595. }
  596. return $task;
  597. }
  598. public static function getTaskNewerUsers() {
  599. $task = null;
  600. $db = DB::getDB();
  601. if (!$db) die("DB Error: No DB! L." . __LINE__);
  602. $sql = "select s.*
  603. from `_SYNC_FILE_PERMS` as s
  604. where s.`ID_PROJECT`=-2
  605. ";
  606. $res = $db->query($sql);
  607. if ($r = $db->fetch($res)) {
  608. $task = $r;
  609. }
  610. if (!$task) {
  611. $task = new stdClass();
  612. $task->ID_PROJECT = -2;
  613. $task->A_SYNC_RESULT = new stdClass();
  614. $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  615. //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  616. }
  617. return $task;
  618. }
  619. public static function getTaskNewFiles() {
  620. $task = null;
  621. $db = DB::getDB();
  622. if (!$db) die("DB Error: No DB! L." . __LINE__);
  623. $sql = "select s.*
  624. from `_SYNC_FILE_PERMS` as s
  625. where s.`ID_PROJECT`=-1
  626. ";
  627. $res = $db->query($sql);
  628. if ($r = $db->fetch($res)) {
  629. $task = $r;
  630. }
  631. if (!$task) {
  632. $task = new stdClass();
  633. $task->ID_PROJECT = -1;
  634. $task->A_SYNC_RESULT = new stdClass();
  635. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  636. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  637. }
  638. return $task;
  639. }
  640. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  641. $task = null;
  642. $db = DB::getDB();
  643. if (!$db) die("DB Error: No DB! L." . __LINE__);
  644. $sqlResult = '';
  645. if ($result) {
  646. $resultJson = json_encode($result);
  647. $resultJson = $db->_($resultJson);
  648. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  649. }
  650. $sql = "update `_SYNC_FILE_PERMS` as s
  651. set
  652. s.`A_LAST_SYNC`=NOW()
  653. , s.`A_SYNCHRONIZED`={$taskDone}
  654. {$sqlResult}
  655. where s.`ID_PROJECT`={$idProject}
  656. ";
  657. $res = $db->query($sql);
  658. return $task;
  659. }
  660. public static function executeTask(&$task) {
  661. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  662. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  663. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  664. $project = new stdClass();
  665. $project->ID = $task->ID_PROJECT;
  666. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  667. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  668. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  669. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  670. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  671. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  672. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  673. $folderConf = FoldersConfig::getAll($confTblName);
  674. $uploader = new FileUploader($confTblName, $project);
  675. $errMsg = '';
  676. if (!$uploader->setConfig($folderConf, $errMsg)) {
  677. trigger_error("Error: folders config!", E_USER_NOTICE);
  678. die("Error: folders config!");
  679. }
  680. $uploader->findFolder();
  681. $mainFolder = $uploader->getDestFolder();
  682. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  683. if (!$mainFolder) {
  684. $mainFolder = $uploader->generateFolderName();
  685. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  686. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  687. mkdir($mainFolderPath, 0770, true);
  688. @chmod($mainFolderPath, 0770);
  689. if (!file_exists($mainFolderPath)) {
  690. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  691. return false;
  692. }
  693. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  694. $file = new stdClass();
  695. $file->name = '.';
  696. $file->path = '.';
  697. //$file->owner = '';
  698. //$file->group = '';
  699. //$file->perms = '';
  700. $file->isDir = true;
  701. $file->permsExt = array();
  702. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  703. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  704. }
  705. else {
  706. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  707. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  708. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  709. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  710. // if folder _PISMA not exists then create
  711. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  712. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  713. if (!empty($cmdKorepList)) {
  714. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
  715. foreach ($cmdKorepList as $vCmd) {
  716. $cmdList[] = $vCmd;
  717. }
  718. }
  719. }
  720. if (!empty($cmdList)) {
  721. foreach ($cmdList as $vCmd) {
  722. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  723. exec($vCmd, $out, $outValue);
  724. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  725. if ($outValue != 0) {
  726. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  727. }
  728. }
  729. }
  730. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  731. }
  732. public static function getActiveLoginList() {
  733. static $activeLoginList;
  734. if (!is_array($activeLoginList)) {
  735. $activeLoginList = array();
  736. $db = DB::getDB();
  737. if (!$db) die("DB Error: No DB! L." . __LINE__);
  738. $sql = "select u.`ADM_ACCOUNT`
  739. from `ADMIN_USERS` as u
  740. where u.`A_STATUS` = 'NORMAL'
  741. ";
  742. $res = $db->query($sql);
  743. while ($r = $db->fetch($res)) {
  744. $activeLoginList[] = $r->ADM_ACCOUNT;
  745. }
  746. }
  747. return $activeLoginList;
  748. }
  749. public static function isActiveUser($login) {
  750. $activeLoginList = self::getActiveLoginList();
  751. return in_array($login, $activeLoginList);
  752. }
  753. public static function getRequiredPermsExtByRecord($project) {
  754. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  755. $requirePermsExt = array();
  756. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  757. // TODO: group PODMIOT
  758. $requirePermsExt["group:workgroup"] = array('write', 'read');
  759. }
  760. else {
  761. if ($project->L_APPOITMENT_USER) {
  762. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  763. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  764. } else {
  765. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  766. }
  767. }
  768. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  769. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  770. }
  771. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  772. $requirePermsExt["group:workgroup"] = array('write', 'read');
  773. }
  774. else {
  775. if ($project->A_ADM_COMPANY) {
  776. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  777. }
  778. if ($project->A_CLASSIFIED) {
  779. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  780. }
  781. }
  782. }
  783. // add parent owner
  784. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  785. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  786. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  787. } else {
  788. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  789. }
  790. }
  791. // add user:_www perms read, write
  792. $requirePermsExt["user:_www"] = array('write', 'read');
  793. return $requirePermsExt;
  794. }
  795. /**
  796. * Used for files added/modified by samba/afp.
  797. *
  798. * @return TODO: object to store in task->A_SYNC_RESULT
  799. */
  800. public static function fixLastModifiedFiles($task) {
  801. $db = DB::getDB();
  802. if (!$db) die("DB Error: No DB! L." . __LINE__);
  803. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  804. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  805. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  806. $foundProjectFiles = array();
  807. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  808. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  809. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  810. if (!empty($filesWithPerms)) {
  811. $filesWithPermsTree = array();
  812. $lastName = '';
  813. foreach ($filesWithPerms as $line) {
  814. if (substr($line, 0, 1) == '-') {// file name
  815. $fileParts = array();
  816. $filePartsArr = explode(' ', $line);
  817. $lastInd = 0;
  818. foreach ($filePartsArr as $vPart) {
  819. if ($lastInd > 7) {// file name
  820. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  821. $lastInd++;
  822. }
  823. else if (!empty($vPart) || $vPart === '0') {
  824. $fileParts[] = $vPart;
  825. $lastInd++;
  826. }
  827. }
  828. $file = new stdClass();
  829. if (!isset($fileParts[8])) {
  830. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  831. //continue;
  832. }
  833. $file->name = end($fileParts);
  834. $file->path = end($fileParts);
  835. //$file->owner = $fileParts[2];
  836. //$file->group = $fileParts[3];
  837. //$file->perms = $fileParts[0];
  838. $file->isDir = (substr($line, 0, 1) == 'd');
  839. $file->permsExt = array();
  840. $filesWithPermsTree[$file->name] = $file;
  841. $lastName = $file->name;
  842. }
  843. else if (substr($line, 0, 1) == ' ') {// extended perm line
  844. if ($lastName == '..') {
  845. continue;
  846. }
  847. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  848. }
  849. else {// parse error
  850. $lastName = '..';
  851. }
  852. }
  853. foreach ($filesWithPermsTree as $vFile) {
  854. $vFile->path = ltrim($vFile->path, './');
  855. $vFile->path = explode('/', $vFile->path);
  856. $vFile->projectFolder = array_shift($vFile->path);
  857. $vFile->path = implode('/', $vFile->path);
  858. $projId = explode('.', $vFile->projectFolder);
  859. $projId = reset($projId);
  860. if (is_numeric($projId) && $projId > 0) {
  861. $foundProjectFiles[$projId][] = $vFile;
  862. }
  863. }
  864. }
  865. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  866. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
  867. if (!empty($foundProjectFiles)) {
  868. $sql = "select p.`ID`
  869. , p.`L_APPOITMENT_USER`
  870. , p.`A_ADM_COMPANY`
  871. , p.`A_CLASSIFIED`
  872. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  873. from IN7_MK_BAZA_DYSTRYBUCJI as p
  874. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  875. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  876. ";
  877. $res = $db->query($sql);
  878. while ($r = $db->fetch($res)) {
  879. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  880. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  881. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  882. if (!empty($cmdList)) {
  883. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  884. foreach ($cmdList as $vCmd) {
  885. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  886. exec($vCmd, $out, $outValue);
  887. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  888. if ($outValue != 0) {
  889. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  890. }
  891. }
  892. } else {
  893. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  894. }
  895. }
  896. }
  897. }
  898. }
  899. public static function fixProjectKoresp($project, $folderPismaPath) {
  900. $db = DB::getDB();
  901. if (!$db) die("DB Error: No DB! L." . __LINE__);
  902. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  903. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  904. $pismaList = array();
  905. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  906. $sql = "select k.`ID`
  907. , k.`K_TYP_KORESP`
  908. from `IN7_DZIENNIK_KORESP` as k
  909. where k.`ID_PROJECT`={$project->ID}
  910. order by k.`ID` DESC
  911. limit 100
  912. ";
  913. $res = $db->query($sql);
  914. while ($r = $db->fetch($res)) {
  915. $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
  916. }
  917. if (empty($pismaList)) {
  918. return false;
  919. }
  920. $lsCmd = array();
  921. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  922. foreach ($pismaList as $kID => $vTyp) {
  923. $lsCmd[] = "{$kID}.*/";
  924. }
  925. if (empty($lsCmd)) {
  926. return false;
  927. }
  928. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  929. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
  930. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  931. $filesWithPermsTree = array();
  932. if (!empty($filesWithPerms)) {
  933. $lastName = '';
  934. $folderParent = '';
  935. foreach ($filesWithPerms as $line) {
  936. if (substr($line, 0, 1) == '-') {// file name
  937. $fileParts = array();
  938. $filePartsArr = explode(' ', $line);
  939. $lastInd = 0;
  940. foreach ($filePartsArr as $vPart) {
  941. if ($lastInd > 7) {// file name
  942. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  943. $lastInd++;
  944. }
  945. else if (!empty($vPart) || $vPart === '0') {
  946. $fileParts[] = $vPart;
  947. $lastInd++;
  948. }
  949. }
  950. $file = new stdClass();
  951. if (!isset($fileParts[8])) {
  952. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  953. //continue;
  954. }
  955. $file->name = end($fileParts);
  956. $file->path = array();
  957. if ($folderParent) $file->path[] = $folderParent;
  958. $file->path[] = end($fileParts);
  959. $file->path = implode('/', $file->path);
  960. //$file->owner = $fileParts[2];
  961. //$file->group = $fileParts[3];
  962. //$file->perms = $fileParts[0];
  963. $file->isDir = (substr($line, 0, 1) == 'd');
  964. $file->permsExt = array();
  965. $filesWithPermsTree[$file->name] = $file;
  966. $lastName = $file->name;
  967. }
  968. else if (substr($line, 0, 1) == ' ') {// extended perm line
  969. if ($lastName == '..') {
  970. continue;
  971. }
  972. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  973. }
  974. else if (substr($line, -1) == ':') {// folder
  975. $folderParent = trim(substr($line, 0, -1), '/');
  976. }
  977. else if (substr($line, 0, 5) == 'total') {
  978. continue;
  979. }
  980. else if (empty($line)) {
  981. $folderParent = '';
  982. continue;
  983. }
  984. else {// parse error
  985. $lastName = '..';
  986. }
  987. }
  988. }
  989. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  990. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
  991. $cmdList = array();
  992. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  993. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  994. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  995. if (!empty($cmdFile)) {
  996. foreach ($cmdFile as $vCmd) {
  997. $cmdList[] = $vCmd;
  998. }
  999. }
  1000. // if folder _PISMA not exists then create
  1001. $fname = explode('/', $vFile->path);
  1002. $fname = end($fname);
  1003. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  1004. }
  1005. return $cmdList;
  1006. }
  1007. /*
  1008. * Not used.
  1009. */
  1010. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  1011. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1012. if (isset($task->A_SYNC_RESULT->total)) {
  1013. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  1014. if (!empty($filesTotal)) {
  1015. $filesTotal = reset($filesTotal);
  1016. $filesTotal = intval(trim($filesTotal));
  1017. $task->A_SYNC_RESULT->total = $filesTotal;
  1018. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  1019. }
  1020. }
  1021. }
  1022. }
  1023. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  1024. $time = time();
  1025. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1026. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za dużo plików ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1027. //return false;
  1028. }
  1029. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1030. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  1031. $filesWithPerms = array();
  1032. $cmd = " ls -Rlea . ";
  1033. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1034. if (isset($task->A_SYNC_RESULT->total)) {
  1035. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
  1036. if ($task->A_SYNC_RESULT->total > 1000) {
  1037. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  1038. if ($lastDone > 0) {
  1039. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  1040. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  1041. } else {
  1042. $task->A_SYNC_RESULT->lastDone = 1000;
  1043. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  1044. }
  1045. }
  1046. }
  1047. }
  1048. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
  1049. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  1050. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
  1051. $filesWithPermsTree = array();
  1052. $lastName = '';
  1053. $folderParent = '';
  1054. foreach ($filesWithPerms as $line) {
  1055. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  1056. $fileParts = array();
  1057. $filePartsArr = explode(' ', $line);
  1058. $lastInd = 0;
  1059. foreach ($filePartsArr as $vPart) {
  1060. if ($lastInd > 7) {// file name
  1061. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1062. $lastInd++;
  1063. }
  1064. else if (!empty($vPart) || $vPart === '0') {
  1065. $fileParts[] = $vPart;
  1066. $lastInd++;
  1067. }
  1068. }
  1069. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  1070. $lastName = '..';
  1071. continue;
  1072. }
  1073. $file = new stdClass();
  1074. if (!isset($fileParts[8])) {
  1075. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1076. //continue;
  1077. }
  1078. $file->name = end($fileParts);
  1079. $file->path = array();
  1080. if ($folderParent) $file->path[] = $folderParent;
  1081. $file->path[] = end($fileParts);
  1082. $file->path = implode('/', $file->path);
  1083. //$file->owner = $fileParts[2];
  1084. //$file->group = $fileParts[3];
  1085. //$file->perms = $fileParts[0];
  1086. $file->isDir = (substr($line, 0, 1) == 'd');
  1087. $file->permsExt = array();
  1088. $filesWithPermsTree[$file->name] = $file;
  1089. $lastName = $file;
  1090. }
  1091. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1092. if ($lastName == '..') {
  1093. continue;
  1094. }
  1095. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1096. }
  1097. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  1098. $folderParent = substr($line, 2, -1);
  1099. }
  1100. else if (substr($line, 0, 5) == 'total') {
  1101. continue;
  1102. }
  1103. else if (empty($line)) {
  1104. $folderParent = '';
  1105. continue;
  1106. }
  1107. }
  1108. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  1109. // check perms
  1110. /*
  1111. files:
  1112. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1113. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1114. R read, execute, readattr, readextattr, readsecurity
  1115. dir:
  1116. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1117. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1118. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1119. */
  1120. $cmdList = array();
  1121. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1122. if (false) {
  1123. // TODO: $kFileName == '_PISMA' - readonly
  1124. // TODO: $vFile->path => _PISMA/...
  1125. }
  1126. else {
  1127. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1128. if (!empty($cmdFile)) {
  1129. foreach ($cmdFile as $vCmd) {
  1130. $cmdList[] = $vCmd;
  1131. }
  1132. }
  1133. }
  1134. }
  1135. return $cmdList;
  1136. }
  1137. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1138. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1139. $cmdList = array();
  1140. $vReqPermsExt = array();
  1141. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1142. $vReqPermsExt[$kPermObj] = array();
  1143. foreach ($vPerms as $vPerm) {
  1144. if ($vFile->isDir) {
  1145. if ($vPerm == 'read') {
  1146. $vReqPermsExt[$kPermObj]['list'] = 0;
  1147. $vReqPermsExt[$kPermObj]['search'] = 0;
  1148. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1149. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1150. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1151. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1152. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1153. }
  1154. else if ($vPerm == 'write') {
  1155. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1156. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1157. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1158. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1159. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1160. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1161. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1162. }
  1163. }
  1164. else {
  1165. if ($vPerm == 'read') {
  1166. $vReqPermsExt[$kPermObj]['read'] = 0;
  1167. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1168. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1169. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1170. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1171. }
  1172. else if ($vPerm == 'write') {
  1173. $vReqPermsExt[$kPermObj]['write'] = 0;
  1174. $vReqPermsExt[$kPermObj]['append'] = 0;
  1175. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1176. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1177. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1178. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1179. }
  1180. }
  1181. }
  1182. }
  1183. $permsToRemove = array();
  1184. foreach ($vFile->permsExt as $vPermExtLine) {
  1185. $vPermExtArr = explode(' ', $vPermExtLine);
  1186. $vPermExt = new stdClass();
  1187. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1188. $vPermExt->permObj = $vPermExtArr[1];
  1189. $vPermExt->perms = '';
  1190. if (count($vPermExtArr) == 4) {
  1191. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1192. }
  1193. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1194. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1195. }
  1196. else {
  1197. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1198. continue;
  1199. }
  1200. $permFound = false;
  1201. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1202. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1203. foreach ($vPerms as $kPerm => $vPermChecked) {
  1204. if (in_array($kPerm, $vPermExt->perms)) {
  1205. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1206. $permFound = true;
  1207. }
  1208. }
  1209. }
  1210. }
  1211. if (!$permFound) {
  1212. $permsToRemove[] = $vPermExt->nr;
  1213. }
  1214. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1215. }
  1216. if (!empty($permsToRemove)) {
  1217. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1218. $permsToRemove = array_reverse($permsToRemove);
  1219. foreach ($permsToRemove as $vPermInd) {
  1220. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1221. }
  1222. }
  1223. $permsToAdd = array();
  1224. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1225. foreach ($vPerms as $kPerm => $vPermChecked) {
  1226. if (!$vPermChecked) {
  1227. $permsToAdd[$kPermObj][$kPerm] = 1;
  1228. }
  1229. }
  1230. }
  1231. if (!empty($permsToAdd)) {
  1232. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1233. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1234. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1235. }
  1236. }
  1237. return $cmdList;
  1238. }
  1239. /**
  1240. * @returns array - last modified project ids.
  1241. */
  1242. public static function fixLastModifiedByFiles() {// TODO: RMME
  1243. $db = DB::getDB();
  1244. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1245. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
  1246. /*
  1247. * $ man find:
  1248. -newer file
  1249. True if the current file has a more recent last modification time than file.
  1250. -newerXY file
  1251. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1252. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1253. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1254. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1255. *
  1256. * $ man chmod:
  1257. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1258. *
  1259. * chmod -a "admin allow write" file1 # remove line
  1260. * chmod -a# 1 file1 # remove line at position 1
  1261. *
  1262. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1263. */
  1264. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1265. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1266. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1267. $foundProjectIds = array();
  1268. $lastRunDate = self::getLastRunDate();
  1269. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1270. if (!empty($foundPaths)) {
  1271. foreach ($foundPaths as $path) {
  1272. $path = ltrim($path, './');
  1273. $folder = explode('/', $path);
  1274. $folder = reset($folder);
  1275. $projId = explode('.', $folder);
  1276. $projId = reset($projId);
  1277. if (is_numeric($projId)) {
  1278. $foundProjectIds[$projId] = $folder;
  1279. }
  1280. }
  1281. }
  1282. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
  1283. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
  1284. if (!empty($foundProjectIds)) {
  1285. $sql = "select p.`ID`
  1286. , p.`L_APPOITMENT_USER`
  1287. , p.`A_ADM_COMPANY`
  1288. , p.`A_CLASSIFIED`
  1289. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1290. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1291. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1292. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1293. ";
  1294. $res = $db->query($sql);
  1295. while ($r = $db->fetch($res)) {
  1296. $mainFolder = $foundProjectIds[$r->ID];
  1297. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1298. if (!empty($cmdList)) {
  1299. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1300. } else {
  1301. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1302. }
  1303. }
  1304. }
  1305. return array_keys($foundProjectIds);
  1306. }
  1307. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1308. $db = DB::getDB();
  1309. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1310. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
  1311. $sqlWhereAdd = '';
  1312. if (!empty($fixedProjIds)) {
  1313. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1314. }
  1315. $projectList = array();
  1316. $lastRunDate = self::getLastRunDate();
  1317. $sql = "select p.`ID`
  1318. , p.`L_APPOITMENT_USER`
  1319. , p.`A_ADM_COMPANY`
  1320. , p.`A_CLASSIFIED`
  1321. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1322. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1323. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1324. where
  1325. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1326. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1327. )
  1328. {$sqlWhereAdd}
  1329. ";
  1330. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1331. $res = $db->query($sql);
  1332. while ($r = $db->fetch($res)) {
  1333. $projectList[$r->ID] = $r;
  1334. }
  1335. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
  1336. }
  1337. public static function getLastRunDate() {// TODO: RMME
  1338. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1339. // Format: 2013-10-07 23:46
  1340. if (strlen($argFromDate) == 16
  1341. && substr($argFromDate, 4, 1) == '-'
  1342. && substr($argFromDate, 7, 1) == '-'
  1343. && substr($argFromDate, 10, 1) == '-'
  1344. && substr($argFromDate, 13, 1) == ':'
  1345. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1346. ) {
  1347. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1348. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1349. }
  1350. }
  1351. if (!$lastRunDate) {
  1352. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1353. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1354. }
  1355. //$lastRunDate = '2013-09-01 01:00';
  1356. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1357. return $lastRunDate;
  1358. }
  1359. public static function usersAction() {
  1360. $task = self::getTaskNewerUsers();
  1361. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1362. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1363. self::saveTask(-2);
  1364. }
  1365. public static function usersAllAction() {
  1366. /*
  1367. * DBU - DB User LDU - LDAP User
  1368. * DBG - DB Group LDG - LDAP Group
  1369. *
  1370. * DBU - ADMIN_USERS
  1371. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1372. *
  1373. * 1. fetch DB Users
  1374. * ? only active users (A_STATUS == 'NORMAL')
  1375. * 2. fetch LDAP Users
  1376. *
  1377. * DBU.ADM_ACCOUNT == LDU.uid
  1378. * DBG.A_LDAP_GID == LDG.gidNumber
  1379. *
  1380. * TODO: $group createLdapGroup()
  1381. *
  1382. */
  1383. Lib::loadClass('UsersHelper');
  1384. $users = self::getUsersAll();
  1385. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1386. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1387. $ldapUsers = array();
  1388. foreach ($allLdapUsers as $vLdapUser) {
  1389. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1390. }
  1391. unset($allLdapUsers);
  1392. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
  1393. foreach ($users as $kLogin => $vUser) {
  1394. if ($vUser->A_STATUS == 'NORMAL') {
  1395. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1396. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1397. }
  1398. else {
  1399. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1400. }
  1401. }
  1402. else if ($vUser->A_STATUS == 'DELETED') {
  1403. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1404. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1405. }
  1406. else {
  1407. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1408. }
  1409. }
  1410. }
  1411. }
  1412. public static function getUsersNewerThen($datetime) {
  1413. $users = array();
  1414. $db = DB::getDB();
  1415. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1416. $sqlWhereAdd = "";
  1417. if ($datetime) {
  1418. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1419. } else {
  1420. // TODO: error datetime not set
  1421. }
  1422. $sql = "select u.ID
  1423. , u.`ADM_ACCOUNT`
  1424. , u.`ADM_NAME`
  1425. , u.`A_STATUS`
  1426. from `ADMIN_USERS` as u
  1427. where
  1428. u.`A_STATUS` in('NORMAL', 'DELETED')
  1429. ";
  1430. $res = $db->query($sql);
  1431. while ($r = $db->fetch($res)) {
  1432. $users[$r->ADM_ACCOUNT] = $r;
  1433. }
  1434. return $users;
  1435. }
  1436. public static function getUsersAll() {
  1437. $users = array();
  1438. $db = DB::getDB();
  1439. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1440. $sql = "select u.ID
  1441. , u.`ADM_ACCOUNT`
  1442. , u.`ADM_NAME`
  1443. , u.`A_STATUS`
  1444. from `ADMIN_USERS` as u
  1445. where
  1446. u.`A_STATUS` in('NORMAL', 'DELETED')
  1447. ";
  1448. $res = $db->query($sql);
  1449. while ($r = $db->fetch($res)) {
  1450. $users[$r->ADM_ACCOUNT] = $r;
  1451. }
  1452. return $users;
  1453. }
  1454. }
  1455. class SyncPermsCustomTables {
  1456. public $_tbls;
  1457. private $_db;
  1458. private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
  1459. private $_activeLoginList;
  1460. public function run() {
  1461. if (!$this->fetchConfig()) return;
  1462. $this->installTable();
  1463. $this->generateTasksNewRecords();
  1464. $this->generateTasksUpdated();
  1465. $this->newFilesAction();
  1466. $limit = 100;
  1467. for ($i = 0; $i < $limit; $i++) {
  1468. $loopTasksFired = 0;
  1469. foreach ($this->_tbls as $tblName => $tblConf) {
  1470. $task = $this->nextTaskAction($tblName);
  1471. if (!$task) {
  1472. // TODO: rm $tblName from config to prevent searching for task in next loops
  1473. unset($this->_tbls[$tblName]);
  1474. continue;
  1475. }
  1476. $loopTasksFired++;
  1477. }
  1478. if (!$loopTasksFired) break;
  1479. $i += $loopTasksFired;
  1480. }
  1481. }
  1482. public function fetchConfig() {
  1483. $this->_db = DB::getDB();
  1484. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1485. $tbls = array();
  1486. $sql = "select c.`CONF_VAL` as tbl_names
  1487. from `CRM_CONFIG` as c
  1488. where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
  1489. ";
  1490. $res = $this->_db->query($sql);
  1491. while ($r = $this->_db->fetch($res)) {
  1492. if (!empty($r->tbl_names)) {
  1493. $tbls = explode("\n", $r->tbl_names);
  1494. }
  1495. }
  1496. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', $tbls) . "]\n";
  1497. $configTbls = array();
  1498. Lib::loadClass('FoldersConfig');
  1499. if (!empty($tbls)) {
  1500. $folderConfAll = FoldersConfig::getRawData();
  1501. foreach ($tbls as $tblName) {
  1502. $tblName = trim($tblName);
  1503. if (empty($tblName)) continue;
  1504. $confTblName = "{$tblName}_COLUMN";
  1505. if (FoldersConfig::hasConfig($confTblName)) {
  1506. $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
  1507. }
  1508. }
  1509. }
  1510. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
  1511. if (!empty($configTbls)) {
  1512. $this->_tbls = $configTbls;
  1513. }
  1514. return $this->_tbls;
  1515. }
  1516. public function installTable() {
  1517. if (!$this->_tbls) return;
  1518. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1519. $sql = "
  1520. CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
  1521. `ID` int(11) NOT NULL AUTO_INCREMENT,
  1522. `TBL_NAME` varchar(64),
  1523. `TBL_ID` int(11) NOT NULL,
  1524. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  1525. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  1526. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  1527. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  1528. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  1529. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  1530. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  1531. `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
  1532. PRIMARY KEY (`ID`),
  1533. UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
  1534. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  1535. ";
  1536. $this->_db->query($sql);
  1537. if ($this->_db->has_errors()) {
  1538. print_r($this->_db->get_errors());
  1539. }
  1540. }
  1541. public function generateTasksNewRecords() {
  1542. if (!$this->_tbls) return;
  1543. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1544. $sqlValues = array();
  1545. foreach ($this->_tbls as $tblName => $tblConf) {
  1546. $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
  1547. }
  1548. $sqlValues = implode(',', $sqlValues);
  1549. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1550. values {$sqlValues};
  1551. ";
  1552. $res = $this->_db->query($sql);
  1553. if ($this->_db->has_errors()) {
  1554. print_r($this->_db->get_errors());
  1555. }
  1556. foreach ($this->_tbls as $tblName => $tblConf) {
  1557. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1558. select '{$tblName}' as TBL_NAME
  1559. , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
  1560. , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
  1561. from `{$tblName}` as t
  1562. where t.`A_STATUS`!='DELETED'
  1563. ";
  1564. $res = $this->_db->query($sql);
  1565. if ($this->_db->has_errors()) {
  1566. print_r($this->_db->get_errors());
  1567. }
  1568. }
  1569. }
  1570. public function generateTasksUpdated() {
  1571. if (!$this->_tbls) return;
  1572. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1573. foreach ($this->_tbls as $tblName => $tblConf) {
  1574. $sql = "update `{$this->_syncTblName}` as s
  1575. , `{$tblName}` as t
  1576. -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
  1577. set
  1578. s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
  1579. , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
  1580. , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
  1581. , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
  1582. , s.`A_SYNCHRONIZED`=0
  1583. where
  1584. s.`TBL_ID`=t.`ID`
  1585. and s.`TBL_NAME`='{$tblName}'
  1586. -- and pt.`ID`=t.`P_ID`
  1587. and (
  1588. s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
  1589. or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
  1590. or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
  1591. -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
  1592. )
  1593. ";
  1594. $res = $this->_db->query($sql);
  1595. if ($this->_db->has_errors()) {
  1596. print_r($this->_db->get_errors());
  1597. }
  1598. }
  1599. }
  1600. public function newFilesAction() {
  1601. if (!$this->_tbls) return;
  1602. foreach ($this->_tbls as $tblName => $tblConf) {
  1603. $task = $this->_getTaskNewFiles($tblName);
  1604. $taskResult = $this->_fixLastModifiedFiles($task);
  1605. $this->_saveTask($tblName, -1);
  1606. }
  1607. }
  1608. private function _getTaskNewFiles($tblName) {
  1609. $task = null;
  1610. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1611. $sql = "select s.*
  1612. from `{$this->_syncTblName}` as s
  1613. where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
  1614. ";
  1615. $res = $this->_db->query($sql);
  1616. if ($r = $this->_db->fetch($res)) {
  1617. $task = $r;
  1618. }
  1619. if (!$task) {
  1620. $task = new stdClass();
  1621. $task->TBL_NAME = $tblName;
  1622. $task->TBL_ID = -1;
  1623. $task->A_SYNC_RESULT = new stdClass();
  1624. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  1625. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  1626. }
  1627. return $task;
  1628. }
  1629. private function _fixLastModifiedFiles($task) {
  1630. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1631. $tblName = $task->TBL_NAME;
  1632. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  1633. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1634. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1635. $record = null;
  1636. $folderConf = FoldersConfig::getAll($confTblName);
  1637. $uploader = new FileUploader($confTblName, $record);
  1638. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1639. trigger_error("Error: folders config!", E_USER_NOTICE);
  1640. die("Error: folders config!");
  1641. }
  1642. $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
  1643. $foundTblFiles = array();
  1644. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  1645. //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  1646. $filesWithPerms = array();
  1647. $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
  1648. exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  1649. if (!empty($filesWithPerms)) {
  1650. $filesWithPermsTree = array();
  1651. $lastName = '';
  1652. foreach ($filesWithPerms as $line) {
  1653. if (substr($line, 0, 1) == '-') {// file name
  1654. $fileParts = array();
  1655. $filePartsArr = explode(' ', $line);
  1656. $lastInd = 0;
  1657. foreach ($filePartsArr as $vPart) {
  1658. if ($lastInd > 7) {// file name
  1659. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1660. $lastInd++;
  1661. }
  1662. else if (!empty($vPart) || $vPart === '0') {
  1663. $fileParts[] = $vPart;
  1664. $lastInd++;
  1665. }
  1666. }
  1667. $file = new stdClass();
  1668. if (!isset($fileParts[8])) {
  1669. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1670. //continue;
  1671. }
  1672. $file->name = end($fileParts);
  1673. $file->path = end($fileParts);
  1674. //$file->owner = $fileParts[2];
  1675. //$file->group = $fileParts[3];
  1676. //$file->perms = $fileParts[0];
  1677. $file->isDir = (substr($line, 0, 1) == 'd');
  1678. $file->permsExt = array();
  1679. $filesWithPermsTree[$file->name] = $file;
  1680. $lastName = $file->name;
  1681. }
  1682. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1683. if ($lastName == '..') {
  1684. continue;
  1685. }
  1686. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1687. }
  1688. else {// parse error
  1689. $lastName = '..';
  1690. }
  1691. }
  1692. foreach ($filesWithPermsTree as $vFile) {
  1693. $vFile->path = ltrim($vFile->path, './');
  1694. $vFile->path = explode('/', $vFile->path);
  1695. $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
  1696. $vFile->path = implode('/', $vFile->path);
  1697. // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
  1698. $tblId = 0;
  1699. if ($hasRecordOwnFolder) {
  1700. $tblId = explode('.', $vFile->recordFolder);
  1701. $tblId = reset($tblId);
  1702. }
  1703. else {
  1704. $tblId = explode('.', $vFile->path);
  1705. $tblId = reset($tblId);
  1706. }
  1707. if (is_numeric($tblId) && $tblId > 0) {
  1708. $foundTblFiles[$tblId][] = $vFile;
  1709. }
  1710. }
  1711. }
  1712. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  1713. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundTblFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($foundTblFiles);echo'</pre>';}
  1714. if (!empty($foundTblFiles)) {
  1715. $rowsIds = array_keys($foundTblFiles);
  1716. $sql = "select t.`ID`
  1717. , t.`L_APPOITMENT_USER`
  1718. , t.`A_ADM_COMPANY`
  1719. , t.`A_CLASSIFIED`
  1720. -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1721. from `{$task->TBL_NAME}` as t
  1722. -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
  1723. where t.`ID` in (" . implode(',', $rowsIds) . ")
  1724. ";
  1725. $res = $this->_db->query($sql);
  1726. while ($r = $this->_db->fetch($res)) {
  1727. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  1728. foreach ($foundTblFiles[$r->ID] as $vFile) {
  1729. $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
  1730. if (!empty($cmdList)) {
  1731. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1732. foreach ($cmdList as $vCmd) {
  1733. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  1734. exec($vCmd, $out, $outValue);
  1735. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  1736. if ($outValue != 0) {
  1737. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  1738. }
  1739. }
  1740. } else {
  1741. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747. private function _getRequiredPermsExtByRecord($record) {
  1748. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  1749. $requirePermsExt = array();
  1750. if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
  1751. // TODO: group PODMIOT
  1752. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1753. }
  1754. else {
  1755. if ($record->L_APPOITMENT_USER) {
  1756. if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
  1757. $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
  1758. } else {
  1759. // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
  1760. }
  1761. }
  1762. if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
  1763. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
  1764. }
  1765. else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
  1766. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1767. }
  1768. else {
  1769. if ($record->A_ADM_COMPANY) {
  1770. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
  1771. }
  1772. if ($record->A_CLASSIFIED) {
  1773. $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
  1774. }
  1775. }
  1776. }
  1777. // add parent owner
  1778. if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
  1779. if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
  1780. $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  1781. } else {
  1782. // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
  1783. }
  1784. }
  1785. // add user:_www perms read, write
  1786. $requirePermsExt["user:_www"] = array('write', 'read');
  1787. return $requirePermsExt;
  1788. }
  1789. private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1790. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1791. $cmdList = array();
  1792. $vReqPermsExt = array();
  1793. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1794. $vReqPermsExt[$kPermObj] = array();
  1795. foreach ($vPerms as $vPerm) {
  1796. if ($vFile->isDir) {
  1797. if ($vPerm == 'read') {
  1798. $vReqPermsExt[$kPermObj]['list'] = 0;
  1799. $vReqPermsExt[$kPermObj]['search'] = 0;
  1800. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1801. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1802. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1803. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1804. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1805. }
  1806. else if ($vPerm == 'write') {
  1807. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1808. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1809. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1810. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1811. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1812. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1813. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1814. }
  1815. }
  1816. else {
  1817. if ($vPerm == 'read') {
  1818. $vReqPermsExt[$kPermObj]['read'] = 0;
  1819. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1820. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1821. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1822. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1823. }
  1824. else if ($vPerm == 'write') {
  1825. $vReqPermsExt[$kPermObj]['write'] = 0;
  1826. $vReqPermsExt[$kPermObj]['append'] = 0;
  1827. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1828. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1829. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1830. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1831. }
  1832. }
  1833. }
  1834. }
  1835. $permsToRemove = array();
  1836. foreach ($vFile->permsExt as $vPermExtLine) {
  1837. $vPermExtArr = explode(' ', $vPermExtLine);
  1838. $vPermExt = new stdClass();
  1839. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1840. $vPermExt->permObj = $vPermExtArr[1];
  1841. $vPermExt->perms = '';
  1842. if (count($vPermExtArr) == 4) {
  1843. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1844. }
  1845. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1846. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1847. }
  1848. else {
  1849. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1850. continue;
  1851. }
  1852. $permFound = false;
  1853. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1854. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1855. foreach ($vPerms as $kPerm => $vPermChecked) {
  1856. if (in_array($kPerm, $vPermExt->perms)) {
  1857. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1858. $permFound = true;
  1859. }
  1860. }
  1861. }
  1862. }
  1863. if (!$permFound) {
  1864. $permsToRemove[] = $vPermExt->nr;
  1865. }
  1866. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1867. }
  1868. if (!empty($permsToRemove)) {
  1869. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1870. $permsToRemove = array_reverse($permsToRemove);
  1871. foreach ($permsToRemove as $vPermInd) {
  1872. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1873. }
  1874. }
  1875. $permsToAdd = array();
  1876. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1877. foreach ($vPerms as $kPerm => $vPermChecked) {
  1878. if (!$vPermChecked) {
  1879. $permsToAdd[$kPermObj][$kPerm] = 1;
  1880. }
  1881. }
  1882. }
  1883. if (!empty($permsToAdd)) {
  1884. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1885. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1886. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1887. }
  1888. }
  1889. return $cmdList;
  1890. }
  1891. private function _isActiveUser($usrLogin) {
  1892. $activeLoginList = $this->_fetchActiveLoginList();
  1893. return in_array($usrLogin, $activeLoginList);
  1894. }
  1895. public function _fetchActiveLoginList() {
  1896. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1897. if (!is_array($this->_activeLoginList)) {
  1898. $this->_activeLoginList = array();
  1899. $sql = "select u.`ADM_ACCOUNT`
  1900. from `ADMIN_USERS` as u
  1901. where u.`A_STATUS` = 'NORMAL'
  1902. ";
  1903. $res = $this->_db->query($sql);
  1904. while ($r = $this->_db->fetch($res)) {
  1905. $this->_activeLoginList[] = $r->ADM_ACCOUNT;
  1906. }
  1907. }
  1908. return $this->_activeLoginList;
  1909. }
  1910. private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
  1911. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1912. $sqlResult = '';
  1913. if ($result) {
  1914. $resultJson = json_encode($result);
  1915. $resultJson = $this->_db->_($resultJson);
  1916. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  1917. }
  1918. $sql = "update `{$this->_syncTblName}` as s
  1919. set
  1920. s.`A_LAST_SYNC`=NOW()
  1921. , s.`A_SYNCHRONIZED`={$taskDone}
  1922. {$sqlResult}
  1923. where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
  1924. ";
  1925. $res = $this->_db->query($sql);
  1926. }
  1927. public function executeTask($tblName, $tblId) {
  1928. if (!$this->_tbls) return;
  1929. $task = $this->_getTask($tblName, $tblId);
  1930. if (!$task) return;
  1931. $this->_executeTask($task);
  1932. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1933. return $task;
  1934. }
  1935. public function nextTaskAction($tblName) {
  1936. if (!$this->_tbls) return;
  1937. $task = $this->_getTask($tblName);
  1938. if (!$task) return;
  1939. $this->_executeTask($task);
  1940. /*
  1941. if (isset($task->A_SYNC_RESULT->total)
  1942. && isset($task->A_SYNC_RESULT->lastDone)
  1943. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  1944. ) {
  1945. $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
  1946. } else {
  1947. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1948. }
  1949. */
  1950. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1951. return $task;
  1952. }
  1953. private function _getTask($tblName, $tblId = null) {
  1954. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1955. $task = null;
  1956. $recordFieldList = $this->_getRecordFieldList($tblName);
  1957. $recordFieldList[] = 'L_APPOITMENT_USER';
  1958. $recordFieldList[] = 'A_ADM_COMPANY';
  1959. $recordFieldList[] = 'A_CLASSIFIED';
  1960. $sqlRecordFields = array();
  1961. foreach ($recordFieldList as $fldName) {
  1962. $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
  1963. }
  1964. $sqlRecordFields = implode(',', $sqlRecordFields);
  1965. $sqlTblId = "and s.`TBL_ID`!=-1";
  1966. if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
  1967. $sql = "select s.*
  1968. , {$sqlRecordFields}
  1969. -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  1970. from `{$this->_syncTblName}` as s
  1971. left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
  1972. -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
  1973. where
  1974. s.`TBL_NAME`='{$tblName}'
  1975. {$sqlTblId}
  1976. and s.`A_SYNCHRONIZED`=0
  1977. and s.`A_POMIN_SYNC`=0
  1978. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  1979. limit 1
  1980. ";
  1981. $res = $this->_db->query($sql);
  1982. if ($r = $this->_db->fetch($res)) {
  1983. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  1984. $task = $r;
  1985. $task->record = new stdClass();
  1986. foreach ($recordFieldList as $fldName) {
  1987. $aliasFldName = "t__{$fldName}";
  1988. $task->record->{$fldName} = $task->{$aliasFldName};
  1989. unset($task->{$aliasFldName});
  1990. }
  1991. }
  1992. return $task;
  1993. }
  1994. private function _getRecordFieldList($tblName) {
  1995. if (empty($this->_tbls[$tblName])) return;
  1996. $conf = $this->_tbls[$tblName];
  1997. $fldNames = array();
  1998. $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
  1999. $fldName = trim($fldName);
  2000. if (!empty($fldName)) $fldNames[$fldName] = true;
  2001. for ($i = 1; $i < 5; $i++) {
  2002. $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
  2003. $fldName = trim($fldName);
  2004. if (!empty($fldName)) $fldNames[$fldName] = true;
  2005. $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
  2006. $fldName = trim($fldName);
  2007. if (!empty($fldName)) $fldNames[$fldName] = true;
  2008. }
  2009. if (!in_array('ID', $fldNames)) {
  2010. $fldNames['ID'] = true;
  2011. }
  2012. return array_keys($fldNames);
  2013. }
  2014. private function _executeTask($task) {
  2015. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  2016. $DBG_TIME = false;
  2017. $dbgTime = new stdClass();
  2018. $dbgTime->startTime = microtime(true);
  2019. $dbgTime->lastTime = $dbgTime->startTime;
  2020. $confTblName = "{$task->TBL_NAME}_COLUMN";
  2021. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  2022. $record = $task->record;
  2023. $folderConf = FoldersConfig::getAll($confTblName);
  2024. $uploader = new FileUploader($confTblName, $record);
  2025. $errMsg = '';
  2026. if (!$uploader->setConfig($folderConf, $errMsg)) {
  2027. trigger_error("Error: folders config!", E_USER_NOTICE);
  2028. die("Error: folders config!");
  2029. }
  2030. if ($DBG_TIME) {
  2031. $dbgTime->curTime = microtime(true);
  2032. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
  2033. $dbgTime->lastTime = $dbgTime->curTime;
  2034. }
  2035. $uploader->findFolder();
  2036. $mainFolder = $uploader->getDestFolder();
  2037. if ($DBG_TIME) {
  2038. $dbgTime->curTime = microtime(true);
  2039. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
  2040. $dbgTime->lastTime = $dbgTime->curTime;
  2041. }
  2042. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  2043. if (!$mainFolder) {
  2044. $mainFolder = $uploader->generateFolderName();
  2045. $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
  2046. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  2047. @mkdir($mainFolderPath, 0770, true);
  2048. @chmod($mainFolderPath, 0770);
  2049. if (!file_exists($mainFolderPath)) {
  2050. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  2051. return false;
  2052. }
  2053. $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
  2054. $file = new stdClass();
  2055. $file->name = '.';
  2056. $file->path = '.';
  2057. //$file->owner = '';
  2058. //$file->group = '';
  2059. //$file->perms = '';
  2060. $file->isDir = true;
  2061. $file->permsExt = array();
  2062. $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
  2063. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$record->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  2064. }
  2065. else {
  2066. $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
  2067. }
  2068. if ($DBG_TIME) {
  2069. $dbgTime->curTime = microtime(true);
  2070. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-generate cmdList - mainFolder(" . (($mainFolder)? 1 : 0) . ")" . "\n";
  2071. $dbgTime->lastTime = $dbgTime->curTime;
  2072. }
  2073. if (!empty($cmdList)) {
  2074. foreach ($cmdList as $vCmd) {
  2075. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  2076. exec($vCmd, $out, $outValue);
  2077. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  2078. if ($outValue != 0) {
  2079. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  2080. }
  2081. }
  2082. }
  2083. if ($DBG_TIME) {
  2084. $dbgTime->curTime = microtime(true);
  2085. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
  2086. $dbgTime->lastTime = $dbgTime->curTime;
  2087. }
  2088. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  2089. }
  2090. public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
  2091. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  2092. $DBG_TIME = false;
  2093. $dbgTime = new stdClass();
  2094. $dbgTime->startTime = microtime(true);
  2095. $dbgTime->lastTime = $dbgTime->startTime;
  2096. $filesWithPerms = array();
  2097. if ($uploader->hasRecordOwnFolder()) {
  2098. $cmd = " ls -Rlea . ";
  2099. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2100. exec($cmd, $filesWithPerms);
  2101. }
  2102. else {
  2103. $lookGlob = $uploader->getFileSearchRegex();
  2104. $cmd = " ls -Rlea {$lookGlob} ";
  2105. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2106. exec($cmd, $filesWithPerms);
  2107. }
  2108. //echo "\n-----------------------\n";
  2109. //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
  2110. if ($DBG_TIME) {
  2111. $dbgTime->curTime = microtime(true);
  2112. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
  2113. $dbgTime->lastTime = $dbgTime->curTime;
  2114. }
  2115. $filesWithPermsTree = array();
  2116. $lastName = '';
  2117. $folderParent = '';
  2118. foreach ($filesWithPerms as $line) {
  2119. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  2120. $fileParts = array();
  2121. $filePartsArr = explode(' ', $line);
  2122. $lastInd = 0;
  2123. foreach ($filePartsArr as $vPart) {
  2124. if ($lastInd > 7) {// file name
  2125. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  2126. $lastInd++;
  2127. }
  2128. else if (!empty($vPart) || $vPart === '0') {
  2129. $fileParts[] = $vPart;
  2130. $lastInd++;
  2131. }
  2132. }
  2133. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  2134. $lastName = '..';
  2135. continue;
  2136. }
  2137. $file = new stdClass();
  2138. if (!isset($fileParts[8])) {
  2139. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  2140. //continue;
  2141. }
  2142. $file->name = end($fileParts);
  2143. $file->path = array();
  2144. if ($folderParent) $file->path[] = $folderParent;
  2145. $file->path[] = end($fileParts);
  2146. $file->path = implode('/', $file->path);
  2147. //$file->owner = $fileParts[2];
  2148. //$file->group = $fileParts[3];
  2149. //$file->perms = $fileParts[0];
  2150. $file->isDir = (substr($line, 0, 1) == 'd');
  2151. $file->permsExt = array();
  2152. $filesWithPermsTree[$file->name] = $file;
  2153. $lastName = $file;
  2154. }
  2155. else if (substr($line, 0, 1) == ' ') {// extended perm line
  2156. if ($lastName == '..') {
  2157. continue;
  2158. }
  2159. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  2160. }
  2161. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  2162. $folderParent = substr($line, 2, -1);
  2163. }
  2164. else if (substr($line, 0, 5) == 'total') {
  2165. continue;
  2166. }
  2167. else if (empty($line)) {
  2168. $folderParent = '';
  2169. continue;
  2170. }
  2171. }
  2172. //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
  2173. if ($DBG_TIME) {
  2174. $dbgTime->curTime = microtime(true);
  2175. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
  2176. $dbgTime->lastTime = $dbgTime->curTime;
  2177. }
  2178. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  2179. // check perms
  2180. /*
  2181. files:
  2182. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  2183. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  2184. R read, execute, readattr, readextattr, readsecurity
  2185. dir:
  2186. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  2187. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  2188. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  2189. */
  2190. $cmdList = array();
  2191. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  2192. if (false) {
  2193. // TODO: $kFileName == '_PISMA' - readonly
  2194. // TODO: $vFile->path => _PISMA/...
  2195. }
  2196. else {
  2197. $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
  2198. if (!empty($cmdFile)) {
  2199. foreach ($cmdFile as $vCmd) {
  2200. $cmdList[] = $vCmd;
  2201. }
  2202. }
  2203. }
  2204. }
  2205. //echo "cmdList: ";print_r($cmdList);echo "\n";
  2206. //echo "\n-----------------------\n";
  2207. if ($DBG_TIME) {
  2208. $dbgTime->curTime = microtime(true);
  2209. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
  2210. $dbgTime->lastTime = $dbgTime->curTime;
  2211. }
  2212. return $cmdList;
  2213. }
  2214. }
  2215. ?>